输入()错误 - 名称错误:名称'...'未定义

2024-03-28 19:40:06 发布

您现在位置:Python中文网/ 问答频道 /正文

当我试图运行这个简单的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

我运行的是MacOSX10.9.1,我使用的是安装Python3.3时附带的PythonLauncher应用程序来运行脚本。

编辑:我意识到我在用2.7运行这些脚本。我想真正的问题是如何在3.3版本中运行我的脚本?我想如果我把我的脚本拖放到Python启动程序应用程序的顶部(Python Launcher应用程序位于my applications文件夹中的Python 3.3文件夹中),它将使用3.3启动我的脚本。我想这个方法仍然会用2.7启动脚本。那我怎么用3.3呢?


Tags: namein脚本文件夹应用程序inputyouris
3条回答

因为您是为Python 3.x编写的,所以您需要以以下内容开始脚本:

#!/usr/bin/env python3

如果您使用:

#!/usr/bin/env python

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

如果你的脚本刚开始:

#! python

然后您可以将其更改为:

#! python3

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

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

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())


在Python2.7中,有两个函数可用于接受用户输入。一个是^{},另一个是^{}。你可以认为他们之间的关系如下

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上下文中不存在的其他内容,它将失败。

>>> 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

Python2.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 again:提示的原因。

所以,最好使用raw_input函数,如下所示

input_variable = raw_input("Enter your name: ")

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

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

您运行的是Python2,而不是Python3。要使其在Python 2中工作,请使用raw_input

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

相关问题 更多 >