为什么Python 3中的`input`会抛出NameError: name...未定义的错误

12

我有一个字符串变量test,在Python 2.x中这很正常。

test = raw_input("enter the test") 
print test

但在 Python 3.x 中,我执行以下操作:

test = input("enter the test") 
print test

使用输入字符串sdas时,我收到了错误消息

Traceback (most recent call last):
 File "/home/ananiev/PycharmProjects/PigLatin/main.py", line 5, in <module>
    test = input("enter the test")
 File "<string>", line 1, in <module> 
NameError: name 'sdas' is not defined

当我在使用Python3编写代码时,使用终端运行Python2时遇到了同样的问题。 - Alejandro Veintimilla
你的 print test 语句不是 Python 3.x 的语法:应该写成 print(test)。现在,Python 会把 test 当作一个命令来执行。 - jcoppens
7个回答

14
您正在使用Python 2解释器运行Python 3代码。如果不是这样,您的print语句会在提示您输入之前抛出SyntaxError

结果是您正在使用Python 2的input,它尝试eval您的输入(可能是sdas),发现它不是有效的Python代码,因此失败了。

Python 3的输入函数在这个视频中有很好的解释:https://www.youtube.com/watch?v=i7Y9ugHJJUg。 - Ishaq Khan

6

我认为你需要的代码是:

test = input("enter the test")
print(test)

否则,由于语法错误,它根本无法运行。在Python 3中,print函数需要括号。但是,我无法重现您的错误。您确定这些行导致了那个错误吗?

1

在像Ubuntu这样的操作系统中,Python已经预装好了。因此默认版本是Python 2.7,您可以通过在终端中输入以下命令来确认版本

python -V

如果您已经安装了它,但没有设置默认版本,您将会看到:
python 2.7

在终端中,我将告诉你如何在Ubuntu中设置默认的Python版本。
一个简单而安全的方法是使用别名。将以下内容放入~/.bashrc~/.bash_aliases文件中:
alias python=python3

在文件中添加上述内容后,运行以下命令:source ~/.bash_aliasessource ~/.bashrc。现在使用python -V再次检查Python版本。如果Python版本为3.x.x,则错误可能在于您的语法,例如使用带有括号的print。将其更改为。
test = input("enter the test")
print(test)

1

我遇到了相同的错误。在终端中输入“python filename.py”时,由于命令中写的是python3,python2试图运行python3代码。当我在终端中输入“python3 filename.py”时,它可以正确运行。希望这对你也有用。


或者在Python脚本中使用shebang :). 更多信息,例如在这里:https://dev59.com/IWw05IYBdhLWcg3w_Guw - s3n0

0

sdas 被视为一个变量。要输入一个字符串,你需要用 " "。


你确定吗?据我所理解,OP想要传递一个已定义的变量,以便脚本可以评估该变量。 - Reporter
你能详细阐述一下你想说的吗?如果你能提供代码片段会更好。 - Rajesh Ujade

0
temperature = input("What's the current temperature in your city? (please use the format ??C or ???F) >>> ")

### warning... the result from input will <str> on Python 3.x only
### in the case of Python 2.x, the result from input is the variable type <int>
### for the <str> type as the result for Python 2.x it's neccessary to use the another: raw_input()

temp_int = int(temperature[:-1])     # 25 <int> (as example)
temp_str = temperature[-1:]          # "C" <str> (as example)

if temp_str.lower() == 'c':
    print("Your temperature in Fahrenheit is: {}".format(  (9/5 * temp_int) + 32      )  )
elif temp_str.lower() == 'f':
    print("Your temperature in Celsius is: {}".format(     ((5/9) * (temp_int - 32))  )  )

-1

如果我们忽略print的语法错误,那么在多个场景下使用input的方法是 -

如果使用Python 2.x:

then for evaluated input use "input"
example: number = input("enter a number")

and for string use "raw_input"
example: name = raw_input("enter your name")

如果使用Python 3.x:
then for evaluated result use "eval" and "input"
example: number = eval(input("enter a number"))

for string use "input"
example: name = input("enter your name")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接