列表的平均值

时间:2016-11-02 00:23:37

标签: python python-3.x

name1 = input("Please enter in your first name :")
name2 = input("Please enter in your last name :")
prompt = "Please enter in your grades. When you are finished, enter 'quit': "
grades = []
grades2 = (input(prompt).strip())
length = len(grades)

while (grades2 != "quit"):
    grades.append(grades2)
    grades2 = input(prompt).strip()

if (grades2 == "quit"):
    average = float( sum(grades) / len(grades) )
    print (name1, name2, average)    

所以我试图让程序打印平均值,我收到了这个错误:

    Traceback (most recent call last):
   File "C:/Users/Owner/AppData/Local/Programs/Python/Python35/Project.py",      line      13, in <module>
          average = float( sum(grades) / len(grades) )
      TypeError: unsupported operand type(s) for +: 'int' and 'str'

帮助!

3 个答案:

答案 0 :(得分:1)

你可以通过修改while循环来解决你的问题,并在检查它是否不是一个退出字符串之后将用户输入转换为浮点数:

name1 = input("Please enter in your first name: ")
name2 = input("Please enter in your last name: ")
prompt = "Please enter in your grades. When you are finished, enter 'quit': "

grades = []

while True:
    an_input = input(prompt).strip()
    if an_input == 'quit': 
         break        
    grades.append(float(an_input))

average = sum(grades) / len(grades)
print(name1, name2, average)

请注意。如果您的用户提供“退出”的其他字符串,则程序将失败。因此,您可能希望扩展到此,以确保用户输入为数字,然后将其附加到成绩列表。

答案 1 :(得分:0)

您的问题是您在列表中追加字符串而不是数字。在将用户输入附加到列表之前,需要将用户输入转换为整数。您可以通过在while循环的每次迭代中打印列表来看到这一点:

Please enter in your first name :dummy
Please enter in your last name :name
Please enter in your grades. When you are finished, enter 'quit': 1
[]
Please enter in your grades. When you are finished, enter 'quit': 2
['1']
Please enter in your grades. When you are finished, enter 'quit': 3
['1', '2']
Please enter in your grades. When you are finished, enter 'quit': 4
['1', '2', '3']
Please enter in your grades. When you are finished, enter 'quit': 5
['1', '2', '3', '4']
Please enter in your grades. When you are finished, enter 'quit': 6
['1', '2', '3', '4', '5']
Please enter in your grades. When you are finished, enter 'quit': 

此外,在将其附加到"quit"列表之前,您应检查用户输入以查看它是否等于字符串grades,以便它不会附加到列表中:

name1 = input("Please enter in your first name :")
name2 = input("Please enter in your last name :")
prompt = "Please enter in your grades. When you are finished, enter 'quit': "
grades = []

while True:
    grade = input("Enter a grade: ")
    if grade == "quit":
        average = sum(grades) / len(grades)
        print(name1, name2, average)
        break
    grades.append(int(grade))

<强>的变化:

  • 我使用了while-true而不是while条件,因为不需要在while循环中测试用户输入以及if语句。
  • 我添加了检查,以确定在您将用户输入附加到grades列表之前用户是否退出。
  • 我将用户输入转换为整数,然后将其附加到grades列表。

答案 2 :(得分:0)

将第二行改为

average = float(sum([float(i) for i in grades]) / len(grades) )