'输入'适用于3.5 IDLE但不在终端中

时间:2016-01-03 23:45:20

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

以下是我所做的一些基本代码:

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但不能在我的终端中工作...... 当我将输入作为" test":

时出现错误
NameError: name 'test' is not defined

任何帮助?

2 个答案:

答案 0 :(得分:4)

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

如果您使用的是Windows,则可以使用Python Launcher(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

答案 1 :(得分:1)

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

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

相关问题