你的逻辑有一些缺陷。在每次在main()中请求用户输入时,都会覆盖user_input的值。您应该做的是,将每个数字收集到list()中。在
Python所引发的错误告诉您的是,内置函数sum()接受传入的一系列数字,而不是单个数字。在
input()函数返回一个字符串,因此需要将输入转换为整数。在
我会把你的程序改写如下:def main():
# create a list to store each grade
# that the user inputs.
grades = []
# while forever
while True:
# get input from the user.
# I am not converting the input to a integer
# here, because were expecting the user to
# enter a string when done.
i = input("Enter grade: ")
# if the user enters 'done' break the loop.
if i == 'done':break
# add the grade the user entered to our grades list.
# converting it to an integer.
grades.append(int(i))
# print the return value
# of the avg function.
print("Grade average:", avg(grades))
def avg(grades):
# return the average of
# the grades.
# note that I'm using the builtin round()
# function here. That is because
# the average is sometimes a
# long decimal. If this does not matter
# to you, you can remove it.
return round(sum(grades)/len(grades), 2)
# call the function main()
main()