【问题标题】:'input' works in 3.5 IDLE but not in the terminal [duplicate]“输入”在 3.5 IDLE 中有效,但在终端中无效 [重复]
【发布时间】:2016-04-07 13:58:03
【问题描述】:

这是我编写的一些基本代码:

userInput = input("Type in a random word:\n")
print("Here are the letters in that word")
for letters in userInput:
    print(letters)

完全可以在 3.5 shell/IDLE 中运行,但不能在我的终端中运行... 这是我将输入作为“测试”时的错误:

NameError: name 'test' is not defined

有什么帮助吗?

【问题讨论】:

  • 您是否在python 控制台中执行此操作(即,在>>> 提示符下)?在 Python 3 REPL 中使用原始输入读取器(如 input() 函数)是有问题的,因为 REPL 已经在读取原始输入。尝试将相同的代码放入文件(例如,“foo.py”)并运行它(例如,python3 foo.py)。这在我的机器上对我来说很好。
  • 不,我将它保存为 ForLoopTest.py ,它仍然给我终端错误。当我得到用户输入时,这个错误仍然存​​在于我的很多练习文件中。
  • 运行 python -V 以查看您在终端中运行的解释器版本。
  • 哦,我明白了。它说我正在运行 Python 2.7.5 我该如何改变它
  • 检查是否安装了 Python 3:which python3。如果是你运行你的程序python3 foo.py 就像上面提到的@BrianClapper。如果它不可用,则必须安装 Python 3。

标签: python python-2.7 python-3.x io terminal


【解决方案1】:

您第二次使用 Python 2 运行代码。您可以使用 python3 而不是使用命令 python,它应该可以工作。

在 Python 2 中,您应该改用 raw_input(),因为输入函数包括对 eval() 函数的调用,该函数尝试将输入作为 Python 代码执行。 raw_input() 将输入作为字符串。在 Python 3 中,raw_input() 已替换为 input()

【讨论】:

  • @G.Grasso 你从一个提供了很好解释的答案变成了一个只提到 Python 版本而不是原因的答案。
  • str(input()) 在 Python 2 中仍然会尝试评估输入并给出相同的错误。 raw_input() 对于 Python 2 是正确的,相当于 Python 3 中的 input()
  • 我已经按照您的描述修复了它。你是对的,我的错。
【解决方案2】:

在终端中,您实际上是在运行 Python 2。Python 2 中的 raw_input() 等同于 Python 3 中的 input()。Python 2 中的 input() 会将输入作为 Python 语句进行评估,因此它会尝试评估test 作为变量名。

如果您使用的是 Windows,则可以使用 Python 启动器 (py.exe) 来指定要运行的 Python 版本(如果您安装了多个版本)。如果您安装了 Python 3,它应该已经在路径中。在 Linux 中 python3 应该可以工作。

例子:

C:\>py -3
Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> input()
test
'test'
>>> ^Z

C:\>py -2
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec  5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> input()
test
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'test' is not defined

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-29
    • 1970-01-01
    • 2021-09-25
    • 2021-01-22
    • 1970-01-01
    相关资源
    最近更新 更多