python program to calculate and print average of subjects and students

Viewed 65

How do i calculate the average of students &subjects. Below is my code but only gives average of students and not subjects

values = []
for i in range(0, 3):
   name = input("enter the name of the first student: ")
   test_1 = int(input("Enter the score on test 1 for the student: "))    

   test_2 = int(input("Enter the score on test 2 for the student: "))
   test_3 = int(input("Enter the score on test 3 for the student: "))
   test_4 = int(input("Enter the score on test 4 for the student: "))
   values.append((name,  (test_1 + test_2 + test_3+test_4) / 4))
for row in values
   print(row)`print(row)
   print("ENTER EXAM SCORE: ")
3 Answers

I think it would be helpful if the arithmetic was delegated out to a separate function such as:

def Average(list):

return sum(list) / len(list)

This way you would be able to call it on all of the test scores or whatever else you wish to implement within the for loop.

It looks like you may benefit from the use of key value pairs(dictionary) to store the data at hand (names: test scores), as well. But this isn't entirely relevent to your question since you can use lists as well.

student_scores = {'Tom': '85.25', 'Jack': '80'}

test_averages = {'test_1': *avg, 'test_2': *avg}

I don't see where you are currently storing the values for each subject in order to calculate this. For example, I would expect to see something like this:

test_1 = [std1_score, std2_score, std3_score, ...etc]

test_2 = [std1_score, std2_score, std3_score, ...etc]

test_3 = [std1_score, std2_score, std3_score, ...etc]

then:

def Average(test_1):

return sum(test_1) / len(test_1)

Instead, it looks like all you are appending to "values" are the student name and their average score per loop without actually saving the test cases for each student as well. There are many ways to do this but figured this could provide a helpful visual of how to go about structuring the code itself.

There you go:

student_grades = {}
test_scores = {1: [], 2: [], 3: [], 4: []}

for i in range(0, 3):
    # `.capitalize()` converts strings like jack, into Jack.
    name = input("Enter the name of the student: ").capitalize()
    
    # Avoiding duplications, when two students have the same name.
    # In such instances, we'll enumerate the students with same name.
    # For example: Jack, Jack(1), Jack(2), etc.
    duplicate_names_count = 1
    _name = name
    while name in student_grades.keys():
        duplicate_names_count += 1
        name = f"{_name}({duplicate_names_count})"
    # Create new student entry on dictionary
    student_grades[name] = []

    # Iterate through `test_scores` keys, to fill each test grades.
    for test_index, test_values in test_scores.items():
        test = int(input(f"Enter the score on Test {test_index} for {name}: "))
        student_grades[name].append(test)

        # Register the givem student grades, to the respective test results.
        test_values.append(test)
    # Compute the average score for the given student
    student_grades[name] = sum(student_grades[name]) / len(student_grades[name])

# Print average score of each student
for student, score in student_grades.items():
    print(f"Test average for {student} is {score:.2f}")

# Print average score of each test
for test_index, test_values in test_scores.items():
    print(f"Test {test_index} average score is {sum(test_values)/len(test_values):.2f}")

# Example:
#
# Enter the name of the student: Tom
# Enter the score on Test 1 for Tom: 90
# Enter the score on Test 2 for Tom: 60
# Enter the score on Test 3 for Tom: 70
# Enter the score on Test 4 for Tom: 80
# Enter the name of the student: Jack
# Enter the score on Test 1 for Jack: 90
# Enter the score on Test 2 for Jack: 90
# Enter the score on Test 3 for Jack: 85
# Enter the score on Test 4 for Jack: 100
# Enter the name of the student: Mary
# Enter the score on Test 1 for Mary: 95
# Enter the score on Test 2 for Mary: 96
# Enter the score on Test 3 for Mary: 97
# Enter the score on Test 4 for Mary: 98
# Test average for Tom is 75.00
# Test average for Jack is 91.25
# Test average for Mary is 96.50
# Test 1 average score is 91.67
# Test 2 average score is 82.00
# Test 3 average score is 84.00
# Test 4 average score is 92.67

Notes

The code is a little lengthy, but it accounts for things like students with the same name. You can also swap test = int(input(f"Enter the score on Test {test_index} for {name}: ")) for a while/loop to ensure the inputted grade stays between 0, and 100.

here is pythonic way to do this, feel free adjust the tests_number and students_number

tests_number = 3
students_number = 4
values = {}

for student in range(students_number):
    name = input("enter the name of the student: ")
    scores = []
    for test in range(tests_number):
        scores.append(
            int(input(f"Enter the score on test {test+1} for the student: "))
        )
    values.update({name: scores})


for name, scores in values.items():
    print(f"Test average for {name} is {sum(scores)/len(scores):.2f}")

for test in range(tests_number):
    test_average = sum(map(lambda x: x[test], values.values())) / tests_number
    print(f"Test {test+1} average is {test_average:.2f}")
Related