繁体   English   中英

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

[英]Python gives error if I run this code from cmd, however runs fine if I run it from Jupyter

我的代码:

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

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 运行它。 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 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM