如何完成重复读取数字的程序,直到用户输入为止 “完成”。输入“完成”后,打印出总数,计数和平均值 数字。如果用户输入的数字不是数字,请检测他们的错误 使用try和except并打印错误消息并跳到下一个数字。
count = 0
total = 0
while True:
x = raw_input('Enter number')
x=int(x)
total = total + x
count = count + 1
average = total / count
print total, count, average
答案 0 :(得分:0)
以下代码应该是您想要的。
count = 0
total = 0
while True:
x = raw_input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print total, count, average
或在Python 3中
count = 0
total = 0
while True:
x = input('Enter number: ')
if(x.lower() == "done"):
break
else:
try:
x=int(x)
total = total + x
count = count + 1
average = total / count
except:
print("That is not an integer. Please try again.")
print(total, count, average)