Python input() 错误 - NameError: name '...' 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21122540/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 22:06:32  来源:igfitidea点击:

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

pythonpython-2.7inputnameerror

提问by chillpenguin

I am getting an error when I try to run this simple script:

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

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

Let's say I type in "dude", the error I am getting is:

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

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

I am running these scripts with Python 2.7.

我正在使用 Python 2.7 运行这些脚本。

回答by chillpenguin

You are running Python 2, not Python 3. For this to work in Python 2, use raw_input.

您正在运行 Python 2,而不是 Python 3。要在 Python 2 中运行,请使用raw_input.

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

回答by thefourtheye

TL;DR

TL; 博士

inputfunction in Python 2.7, evaluates whatever your enter, as a Python expression. If you simply want to read strings, then use raw_inputfunction in Python 2.7, which will not evaluate the read strings.

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

If you are using Python 3.x, raw_inputhas been renamed to input. Quoting the Python 3.0 release notes,

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

raw_input()was renamed to input(). That is, the new input()function reads a line from sys.stdinand returns it with the trailing newline stripped. It raises EOFErrorif the input is terminated prematurely. To get the old behavior of input(), use eval(input())

raw_input()已重命名为input(). 也就是说,新input()函数从中读取一行sys.stdin并将其返回,并去掉尾部的换行符。EOFError如果输入过早终止,它会引发。要获得 的旧行为input(),请使用eval(input())



In Python 2.7, there are two functions which can be used to accept user inputs. One is inputand the other one is raw_input. You can think of the relation between them as follows

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

input = eval(raw_input)

Consider the following piece of code to understand this better

考虑以下代码以更好地理解这一点

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

inputaccepts a string from the user and evaluates the string in the current Python context. When I type dudeas input, it finds that dudeis bound to the value thefourtheyeand so the result of evaluation becomes thefourtheyeand that gets assigned to input_variable.

input接受来自用户的字符串并评估当前 Python 上下文中的字符串。当我输入dude作为输入时,它发现dude绑定到该值thefourtheye,因此评估结果变为thefourtheye并且被分配给input_variable.

If I enter something else which is not there in the current python context, it will fail will the NameError.

如果我输入当前 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

Security considerations with Python 2.7's input:

Python 2.7 的安全注意事项input

Since whatever user types is evaluated, it imposes security issues as well. For example, if you have already loaded osmodule in your program with import os, and then the user types in

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

os.remove("/etc/hosts")

this will be evaluated as a function call expression by python and it will be executed. If you are executing Python with elevated privileges, /etc/hostsfile will be deleted. See, how dangerous it could be?

这将被python评估为函数调用表达式,并将被执行。如果您使用提升的权限执行 Python,/etc/hosts文件将被删除。看,这有多危险?

To demonstrate this, let's try to execute inputfunction again.

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

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

Now, when input("Enter your name: ")is executed, it waits for the user input and the user input is a valid Python function invocation and so that is also invoked. That is why we are seeing Enter your name again:prompt again.

现在,当input("Enter your name: ")被执行时,它等待用户输入并且用户输入是一个有效的 Python 函数调用,因此它也会被调用。这就是我们Enter your name again:再次看到提示的原因。

So, you are better off with raw_inputfunction, like this

所以,你最好使用raw_input功能,像这样

input_variable = raw_input("Enter your name: ")

If you need to convert the result to some other type, then you can use appropriate functions to convert the string returned by raw_input. For example, to read inputs as integers, use the intfunction, like shown in this answer.

如果需要将结果转换为其他类型,则可以使用适当的函数将raw_input. 例如,要将输入读取为整数,请使用此答案中int所示的函数。

In python 3.x, there is only one function to get user inputs and that is called input, which is equivalent to Python 2.7's raw_input.

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

回答by Zim

Since you are writing for Python 3.x, you'll want to begin your script with:

由于您正在为 Python 3.x 编写代码,因此您需要从脚本开始:

#!/usr/bin/env python3

If you use:

如果您使用:

#!/usr/bin/env python

It will default to Python 2.x. These go on the first line of your script, if there is nothing that starts with #!(aka the shebang).

它将默认为 Python 2.x。如果没有以#! (又名shebang)。

If your scripts just start with:

如果您的脚本只是从以下内容开始:

#! python

Then you can change it to:

然后您可以将其更改为:

#! python3

Although this shorter formatting is only recognized by a few programs, such as the launcher, so it is not the best choice.

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

The first two examples are much more widely used and will help ensure your code will work on any machine that has Python installed.

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

回答by automonous

For anyone else that may run into this issue, turns out that even if you include #!/usr/bin/env python3at the beginning of your script, the shebang is ignored if the file isn't executable.

对于可能遇到此问题的任何其他人,即使您#!/usr/bin/env python3在脚本的开头包含,如果文件不可执行,shebang 也会被忽略。

To determine whether or not your file is executable:

要确定您的文件是否可执行:

  • run ./filename.pyfrom the command line
  • if you get -bash: ./filename.py: Permission denied, run chmod a+x filename.py
  • run ./filename.pyagain
  • 运行./filename.py在命令行
  • 如果你得到-bash: ./filename.py: Permission denied,运行chmod a+x filename.py
  • ./filename.py再次运行

If you've included import sys; print(sys.version)as Kevin suggested, you'll now see that the script is being interpreted by python3

如果您已import sys; print(sys.version)按照 Kevin 的建议包含在内,您现在将看到该脚本正在被 python3 解释

回答by Cleve Green

You can change which python you're using with your IDE, if you've already downloaded python 3.x it shouldn't be too hard to switch. But your script works fine on python 3.x, I would just change

您可以更改您在 IDE 中使用的 python,如果您已经下载了 python 3.x,切换应该不会太难。但是你的脚本在 python 3.x 上运行良好,我只想改变

print ("your name is" + input_variable)

to

print ("your name is", input_variable)

Because with the comma it prints with a whitespace in between your name isand whatever the user inputted. AND: if you're using 2.7 just use raw_inputinstead of input.

因为使用逗号,它会your name is在用户输入的任何内容之间打印一个空格。并且:如果您使用的是 2.7,只需使用raw_input而不是输入。

回答by Abdullah Baraka

You could either do:

你可以这样做:

x = raw_input("enter your name")
print "your name is %s " % x

or:

或者:

x = str(input("enter your name"))
print "your name is %s" % x

回答by RAHUL KUMAR

For python 3 and above

对于python 3及以上

s = raw_input()

it will solve the problem on pycharm IDE if you are solving on online site exactly hackerrank then use:

如果您正在在线网站上解决hackerrank,它将解决pycharm IDE上的问题,然后使用:

s = input()

回答by Skiller Dz

You should use raw_inputbecause you are using python-2.7. When you use input()on a variable (for example: s = input('Name: ')), it will execute the command ON the Python environment without saving what you wrote on the variable (s) and create an error if what you wrote is not defined.

您应该使用,raw_input因为您使用的是 python-2.7。当您input()在变量上使用时(例如: s = input('Name: ')),它将在 Python 环境中执行命令而不保存您在变量 ( s)上写的内容,如果您写的内容未定义,则会产生错误。

raw_input()will save correctly what you wrote on the variable (for example: f = raw_input('Name : ')), and it will not execute it in the Python environment without creating any possible error:

raw_input()将正确保存您在变量上写的内容(例如:)f = raw_input('Name : '),并且不会在 Python 环境中执行它而不会产生任何可能的错误:

input_variable = raw_input('Enter Your Name : ')
print("Your Name Is  : " + (input_variable))

回答by Parminder Singh

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

You have to enter input in either single or double quotes

您必须以单引号或双引号输入

Ex:'dude' -> correct

    dude -> not correct

回答by Hardian

We are using the following that works both python 2 and python 3

我们正在使用以下适用于python 2 和 python 3

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Enter your name: "))