python - 输入()错误 - NameError : name '...' is not de

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

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

最佳答案

TL;DR

Python 2.7 中的

input 函数将您输入的任何内容作为 Python 表达式求值。如果您只是想读取字符串,请使用 Python 2.7 中的 raw_input 函数,该函数不会评估读取的字符串。

如果您使用的是 Python 3.x,则 raw_input 已重命名为 input。引用 Python 3.0 release notes ,

raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use 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 绑定(bind)到值 thefourtheye 因此评估结果变为 thefourtheye 并将其分配给 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 的安全注意事项:

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

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

input_variable = raw_input("Enter your name: ")

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

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

关于python - 输入()错误 - NameError : name '...' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21122540/

相关文章:

python - 从数字中获取月份名称

python - 如何在 Python 中将字符串转换为 double 值?

linux - 第一次如何配置postgresql?

python - 从字符串中删除所有特殊字符、标点符号和空格

linux - 什么是 .pid 文件,它包含什么?

linux - 如何快速汇总文件中的所有数字?

linux - 如何将 time 命令的输出重定向到 Linux 中的文件?

python - 为什么需要在 Python 方法中显式使用 "self"参数?

python - 让 virtualenv 从你的全局站点包中继承特定的包

linux - 更改用户默认主目录的命令