我得到以下语法错误:TypeError:不支持+:“int”和“str”的操作数类型

2024-05-15 09:32:08 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我必须回答的问题:

编写一个程序输入考试成绩(满分100分),直到你输入“退出”。输入完考试成绩后,程序将打印出所有考试成绩的平均值。在

提示: 要计算出平均数,你必须保持一个总的考试成绩和计数的数字输入。 试着让程序运行一次,然后找出退出条件并使用whiletrue:循环。在

示例运行: 输入考试分数或键入“退出”:100 输入考试分数或键入“退出”:100 输入考试分数或键入“退出”:50 输入考试成绩或键入'quit':退出 分数3。平均83.33

这是我的代码:

count = 0
average = sum
while True:
    num =input('Enter an exam score or type "quit":')
    count = count + 1
    average = sum(num)
    print ('the total of exams is %d and the average is %f' % count, average)
    if num == 'quit':
        break
print ('this is ok for now')

Tags: the程序键入iscountnumquit平均值
2条回答

我的想法是使用statistics模块和sys退出。还可以处理非整型(或非浮点型)输入并打印正确的消息,而不是用ValueError退出

import statistics, sys

notes = []
count = 0
average = 0   # or None
while True:
    note = input('Enter score: ')
    # handle quit request first, skip any calculation
    # if quit is the first request
    if note == 'quit':
        print('Program exit. Average is %s' % average)
        sys.exit()
    else:
        # test if the entered data can be an int or float
        try:
            note = int(note)     # can be replaced with float(note) if needed
            count += 1           # increase the counter
            notes.append(int(note))
            average = statistics.mean(notes)    # calculate the average (mean)
            print('Total %s average is %s' % (count, average))
        # just print an error message otherwise and continue
        except ValueError:
            print('Please enter a valid note or "quit"')

这一行有很多问题:average = sum(num)。在

sum的适当输入是要求和的一系列数字。在你的例子中,你只有一个数字或者单词“quit”。在

您需要做的是跟踪计数和总计数,然后在最后进行除法:

total = 0
count = 0
while True:
    # With raw_input, we know we are getting a string instead of
    # having Python automatically try to interpret the value as the
    # correct type
    num = raw_input('Enter an exam score or type "quit":')
    if num == "quit":
        break
    # Convert num from a string to an integer and add it to total
    total += int(num)
    count = count + 1
average = total / count
print("The total number of exams is {} and the average is {}".format(count, average))

相关问题 更多 >