【发布时间】:2020-03-12 15:22:57
【问题描述】:
我的代码:
基本上,我正在阅读列表中的输入。如果它不是整数,它应该给出一个错误,并在我写“完成”时跳过该输入并停止。然后我创建一个计数、总和和平均值,然后打印出来。
total = 0
count = 0
list = []
while True:
num = input("Enter a number: ")
if num == "done":
break
try:
fnum = float(num)
list.append(fnum)
except:
print("Invalid input")
print(fnum, type(fnum))
continue
print(list)
for i in list:
count += 1
total += i
print(total, count, "Average: ", total/count)
错误信息
就像我说的,它在 Jupyter 或 Colab 上运行良好,但我从 cmd 收到以下错误消息:
如果我输入一个随机字符串:
Traceback (most recent call last):
File "C:location\file.py", line 6, in <module>
num = input("Enter a number: ")
File "<string>", line 1, in <module>
NameError: name 'asd' is not defined
如果我输入完成:
Traceback (most recent call last):
File "C:location\file.py", line 6, in <module>
num = input("Enter a number: ")
File "<string>", line 1, in <module>
NameError: name 'done' is not defined
【问题讨论】:
-
你是在 python 2 中运行这个吗?
-
像这样使用
except是不好的做法,请参阅stackoverflow.com/questions/54948548/…。给变量命名list也是个糟糕的主意,要小心! -
谢谢!是的,不幸的是我在 python 2 中运行它。但是当我在 cmd 中输入 python3 时,它工作了
标签: python input while-loop try-except