简体   繁体   中英

Sum and Average from user input

I'm having some trouble with creating a program to compute the average of some test scores. I am receiving an error along the lines of "expected type 'int', got 'none' instead". I understand what this means, but I don't know why it's happening.

Here is my code:

#Get information from user, declare and define variables
name = input("Please enter your name")
howManyTests = int(input('How many test scores are you entering?'))
#For loop to calculate test grade average
for n in range(howManyTests):
    lst = []
    grades = float(input('Enter test grade: '))
    sum_grades = lst.append(grades)
testavg = sum_grades/howManyTests
print('Hi ',name,' your average of ',howManyTests, ' tests is :', testavg)

There are two issues with your code:

  1. lst.append(grades) returns None , because it modifies the lst list in-place. Don't assign its return value to a variable.
  2. You're reassigning the lst variable to an empty list at the beginning of every iteration of the for loop -- as a result, it will contain only one element after you've exited the loop.

Here is a code snippet that fixes both of these issues:

#Get information from user, declare and define variables
name = input("Please enter your name")
howManyTests = int(input('How many test scores are you entering?'))
#For loop to calculate test grade average
lst = []
for n in range(howManyTests):
    grades = float(input('Enter test grade: '))
    lst.append(grades)
testavg = sum(lst)/howManyTests
print('Hi ',name,' your average of ',howManyTests, ' tests is :', testavg)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM