如果我从cmd运行此代码,Python会出错,但如果我从Jupyter运行,它会运行良好



我的代码:

基本上,我在阅读列表中的输入。如果不是整数,它应该给出一个错误,并跳过该输入,当我写"done"时停止。然后我创建一个计数、总和和平均值,并打印出来。

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:locationfile.py", line 6, in <module>
num = input("Enter a number: ")
File "<string>", line 1, in <module>
NameError: name 'asd' is not defined

如果我输入done:

Traceback (most recent call last):
File "C:locationfile.py", line 6, in <module>
num = input("Enter a number: ")
File "<string>", line 1, in <module>
NameError: name 'done' is not defined

可能您正在使用Python 2运行它。Jupyter使用Python 3,所以没问题。然而,在python2中,input()函数接受一个输入并将其作为代码执行。您输入了asd-,python抱怨没有asd变量(与done相同(。使用python 3运行它,或者使用raw_input()函数,它与python 3中的input()具有相同的效果,但在python 2中(即没有运行代码(。

编辑:

假设您正在使用python filename.py来运行代码,请尝试python -V。我会给你python版本。如果我纠正了,大多数情况下,您可以使用python3而不是仅使用python访问python3。

相关内容

最新更新