输入()错误 - NameError:名称“...”未定义

2023-12-08

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

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

inputPython 2.7 中的函数,将您输入的任何内容作为 Python 表达式进行计算。如果你只是想读取字符串,那么使用raw_inputPython 2.7 中的函数,它不会评估读取的字符串。

如果您使用的是 Python 3.x,raw_input已更名为input。引用Python 3.0 发行说明,

raw_input()被重命名为input()。也就是说,新的input()函数读取一行sys.stdin并返回它并删除尾随换行符。它提高了EOFError如果输入提前终止。为了获得旧的行为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与值绑定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:

由于评估任何用户类型,它也会带来安全问题。例如,如果您已经加载了os程序中的模块import os,然后用户输入

os.remove("/etc/hosts")

this 将被 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.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

输入()错误 - NameError:名称“...”未定义 的相关文章

随机推荐