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

新手上路,请多包涵

当我尝试运行这个简单的脚本时出现错误:

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

假设我输入“dude”,我得到的错误是:

   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 应用程序来运行脚本。

原文由 chillpenguin 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 624
1 个回答

长话短说

input Python 2.7 中的函数,计算您输入的任何内容,作为 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 上下文中评估该字符串。 When I type dude as input, it finds that dude is bound to the value thefourtheye and so the result of evaluation becomes thefourtheye and被分配给 input_variable

如果我输入当前 python 上下文中不存在的其他内容,它将失败 NameError

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

Python 2.7 的安全注意事项 input

由于评估了任何用户类型,因此它也会带来安全问题。例如,如果您已经在程序中加载了 os 模块 import 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 函数调用,因此它也被调用。这就是我们再次看到 Enter your name again: 提示的原因。

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

input_variable = raw_input("Enter your name: ")

如果您需要将结果转换为其他类型,则可以使用适当的函数来转换 raw_input 返回的字符串。例如,要将输入读取为整数,请使用 int 函数,如 本答案 所示。

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

原文由 thefourtheye 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题