[英]A python program that reads numbers and stops when you enter 'done' using try and except
I tried writing a program that reads numbers using a loop, evaluates the total numbers, prints it and stops when you type done using try and except.我尝试编写一个程序,该程序使用循环读取数字,评估总数,打印它并在您使用 try 和 except 键入完成时停止。
initiator = True
myList = []
while initiator:
try:
userIn = int(input('Enter any number >> '))
myList.append(userIn)
print(myList)
except ValueError:
if str(userIn):
if userIn == 'done':
pass
average = eval(myList)
print(average)
initiator = False
else:
print('Wrong input!\nPlease try again')
continue
When int()
raises an exception, it doesn't set userIn
, so you can't compare userIn
with done
.当
int()
引发异常时,它不会设置userIn
,因此您无法将userIn
与done
比较。
You should separate reading the input and callint int()
.您应该分开读取输入和 callint
int()
。
while True:
try:
userIn = input('Enter any number >> ')
num = int(userIn)
myList.append(num)
print(myList)
except ValueError:
if userIn == 'done':
break
else:
print('Wrong input!\nPlease try again')
average = sum(myList) / len(myList)
print(average)
eval()
is not the correct way to get the average of a list. eval()
不是获取列表平均值的正确方法。 Use sum()
to add up the list elements, and divide by the length to get the average.使用
sum()
将列表元素相加,然后除以长度以获得平均值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.