input()错误 - NameError: name '...' is not defined

当我试图运行这个简单的python脚本时,我得到了一个错误。

input_variable = input ("Enter your name: ")
print ("your name is" + input_variable)

假设我输入"老兄",我得到的错误是。

line 1, in <module>
input_variable = input ("Enter your name: ")
File "<string>", line 1, in <module>
NameError: name 'dude' is not defined

我运行的是Mac OS X 10.9.1,我使用Python 3.3安装时附带的Python Launcher应用程序来运行脚本。

编辑:我意识到我是以某种方式用2.7运行这些脚本。我想真正的问题是我如何在3.3版本中运行我的脚本?我想,如果我把我的脚本拖放到Python Launcher应用程序上面,该应用程序位于我的应用程序文件夹中的Python 3.3文件夹内,它将使用3.3版本启动我的脚本。我想这种方法仍然是用 2.7 启动脚本。那么,我如何使用 3.3 呢?

TL;DR

在Python 2.7中的input函数,评估你输入的任何东西,作为一个Python表达式。如果你只是想读取字符串,那么使用Python 2.7中的raw_input函数,它不会对读取的字符串进行评估。

如果你使用的是Python 3.x,raw_input已经被改名为input。引用Python 3.0 发行说明

raw_input()被改名为input()。也就是说,新的input()函数从sys.stdin中读取一行,并在返回时去掉尾部的换行。如果输入被提前终止,它将引发EOFError'。要获得input()的旧行为,使用eval(input())`。


在Python 2.7中,有两个函数可以用来接受用户输入。一个是 input,另一个是 raw_input。你可以认为它们之间的关系如下

input = eval(raw_input)

考虑一下下面这段代码,以便更好地理解这一点

>>> dude = "thefourtheye"
>>> input_variable = input("Enter your name: ")
Enter your name: dude
>>> input_variable
'thefourtheye'

input从用户那里接受一个字符串,并在当前的Python上下文中对该字符串进行评估。当我输入 "dude "时,它发现 "dude "被绑定到 "thefourtheye "这个值上,所以评估的结果变成了 "thefourtheye",并被分配给 "input_variable"。

如果我输入其他东西,而这些东西在当前的Python上下文中并不存在,那么它将会出现`NameError'。

>>> input("Enter your name: ")
Enter your name: dummy
Traceback (most recent call last):
  File "<input>", line 1, in 
  File "", line 1, in 
NameError: name 'dummy' is not defined

Python 2.7'的input的安全考虑:

因为无论用户输入什么都会被评估,所以也会带来安全问题。例如,如果你已经用import os在你的程序中加载了os模块,然后用户输入了

os.remove("/etc/hosts")

这将被python评估为一个函数调用表达式,并被执行。如果你以高权限执行Python,/etc/hosts文件将被删除。你看,这有多危险?

为了证明这一点,让我们再次尝试执行input函数。

>>> dude = "thefourtheye"
>>> input("Enter your name: ")
Enter your name: input("Enter your name again: ")
Enter your name again: dude

现在,当input("Enter your name: ")被执行时,它在等待用户输入,用户输入是一个有效的Python函数调用,所以也被调用。这就是为什么我们会看到再次输入你的名字:的提示。

所以,你最好使用raw_input函数,像这样

input_variable = raw_input("Enter your name: ")

如果你需要将结果转换为其他类型,那么你可以使用适当的函数来转换raw_input返回的字符串。例如,要把输入读成整数,可以使用int函数,就像本答案中所示。

在python 3.x中,只有一个函数可以获得用户输入,它被称为input,它相当于Python 2.7'的raw_input

评论(0)

你正在运行Python 2,而不是Python 3。 要想在Python 2中工作,请使用raw_input

input_variable = raw_input ("Enter your name: ")
print ("your name is" + input_variable)
评论(0)

因为你是为Python 3.x编写的,所以你想用以下方式开始你的脚本。

#!/usr/bin/env python3

如果你使用

#!/usr/bin/env python

它将默认为Python 2.x。如果没有以#!开头的内容(又称shebang),这些内容将放在脚本的第一行。

如果你的脚本只是以:

#! python

那么你可以把它改成。

#! python3

虽然这种较短的格式只被少数程序识别,如启动器,所以它不是最佳选择。

前两个例子使用得更广泛,将有助于确保你的代码能在任何安装了Python的机器上工作。

评论(0)