尝试使用哨兵控制循环来添加和平均一堆整数

Trying to use a sentinel controlled loop to add and average a bunch of integers

我想把一堆数字加在一起,最后的数字是哨兵(999)。如果键入 999,则输入循环结束并打印答案,否则它会继续循环并添加输入。但是当我运行程序时,它显示错误:

Traceback (most recent call last):
  File "lab9.py", line 4, in <module>
    sum += kbInput
TypeError: unsupported operand type(s) for +=: 'builtin_function_or_method' and 'int'

代码如下:

kbInput = input()
while int(kbInput) != 999:
        kbInput = input()
        sum += kbInput
        count += 1
        average = sum/average
print("Sum", sum)
print("Average", average)

sum 是内置函数。使用名称 sum_ 并在循环之前将其设置为零:

sum_ = 0
count = 0
while True:
    kbInput = float(input())
    if kbInput == 999:
        break
    sum_ += kbInput
    count += 1
average = sum_ / count
print("Sum", sum_)
print("Average", average)