【问题标题】:Python gives error if I run this code from cmd, however runs fine if I run it from Jupyter如果我从 cmd 运行此代码,Python 会出错,但是如果我从 Jupyter 运行它,则运行良好
【发布时间】: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


【解决方案1】:

您可能正在使用 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。

【讨论】:

  • 哇,非常感谢!我确实使用了 python 而不是 python3,这解决了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
  • 1970-01-01
  • 1970-01-01
  • 2021-10-09
  • 2018-09-11
  • 2020-10-01
相关资源
最近更新 更多