input()错误-NameError:名称“ …”未定义

问题:input()错误-NameError:名称“ …”未定义

尝试运行此简单脚本时出现错误:

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

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

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:

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.


回答 0

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(),请使用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")

它将由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中,只有一个函数可以获取用户输入,该函数称为inputpython 2.7的raw_input

TL;DR

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

If you are using Python 3.x, raw_input has been renamed to input. Quoting the 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())


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

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'

input accepts a string from the user and evaluates the string in the current Python context. 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 that gets assigned to input_variable.

If I enter something else which is not there in the current python context, it will fail will the 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:

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

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/hosts file will be deleted. See, how dangerous it could be?

To demonstrate this, let’s try to execute input function again.

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

So, you are better off with raw_input function, like this

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 int function, like shown in this answer.

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.


回答 1

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

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

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

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

回答 2

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

#!/usr/bin/env python3

如果您使用:

#!/usr/bin/env python

它将默认为Python2.x。如果没有以开头的内容,它们将放在脚本的第一行(又名shebang)。

如果您的脚本仅以以下内容开头:

#! python

然后,您可以将其更改为:

#! python3

尽管只有一些程序(例如启动器)可以识别这种较短的格式,但这并不是最佳选择。

前两个示例被广泛使用,将有助于确保您的代码在安装了Python的任何计算机上都能正常工作。

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

#!/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).

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.


回答 3

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

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

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

You should use raw_input because 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() 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:

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

回答 4

对于python 3及更高版本

s = raw_input()

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

s = input()

For python 3 and above

s = raw_input()

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

s = input()

回答 5

您可以这样做:

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

要么:

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

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

回答 6

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

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

Ex:'dude' -> correct

    dude -> not correct
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

回答 7

我还遇到了一个本应与python 2.7和3.7兼容的模块的问题

我发现解决问题的是导入:

from six.moves import input

这固定了两个口译员的可用性

你可以在这里阅读更多关于六个图书馆的信息

I also encountered this issue with a module that was supposed to be compatible for python 2.7 and 3.7

what i found to fix the issue was importing:

from six.moves import input

this fixed the usability for both interpreters

you can read more about the six library here


回答 8

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

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

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

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

回答 9

对于可能会遇到此问题的其他任何人,事实证明,即使您#!/usr/bin/env python3在脚本的开头添加了该文件,如果该文件不可执行,也将忽略shebang。

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

  • 运行./filename.py在命令行
  • 如果得到-bash: ./filename.py: Permission denied,请运行chmod a+x filename.py
  • 再跑./filename.py一次

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

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

To determine whether or not your file is executable:

  • run ./filename.py from the command line
  • if you get -bash: ./filename.py: Permission denied, run chmod a+x filename.py
  • run ./filename.py again

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


回答 10

以前的贡献不错。

import sys; print(sys.version)

def ingreso(nombre):
    print('Hi ', nombre, type(nombre))

def bienvenida(nombre):
    print("Hi "+nombre+", bye ")

nombre = raw_input("Enter your name: ")

ingreso(nombre)
bienvenida(nombre)

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Your name: "))
输入您的姓名:Joe
(“嗨”,“乔”,<类型“ str”>)
嗨乔,再见 

您的名字:Joe
乔

谢谢!

Good contributions the previous ones.

import sys; print(sys.version)

def ingreso(nombre):
    print('Hi ', nombre, type(nombre))

def bienvenida(nombre):
    print("Hi "+nombre+", bye ")

nombre = raw_input("Enter your name: ")

ingreso(nombre)
bienvenida(nombre)

#Works in Python 2 and 3:
try: input = raw_input
except NameError: pass
print(input("Your name: "))
Enter your name: Joe
('Hi ', 'Joe', &lttype 'str'&gt)
Hi Joe, bye 

Your name: Joe
Joe

Thanks!


回答 11

有两种方法可以解决这些问题,

  • 第一个很简单,无需更改代码,该代码
    由Python3运行,
    如果您仍然想在python2上运行,那么在运行python脚本后,输入输入时请记住

    1. 如果要输入,string则只需使用“ input go with double-quote”输入即可,它将在python2.7和
    2. 如果您想输入字符,请在输入中使用单引号,例如“您的输入在此处”
    3. 如果您想输入数字而不是问题,只需键入数字
  • 第二种方法是代码更改,
    使用以下导入并与任何版本的python一起运行

    1. from six.moves import input
    2. 在任何导入中使用raw_input()函数代替input()代码中的函数
    3. 使用str()like函数清理代码,str(input())然后将其分配给任何变量

错误提示
未定义名称“ dude”,即python的“ dude”在此处变为变量,并且没有分配任何python定义的类型的值,
因此只能像婴儿一样哭泣,因此如果我们定义“ dude”变量并分配任何值并传递给它,它将起作用,但这不是我们想要的,因为我们不知道用户将输入什么,此外,我们还希望捕获用户输入。

关于这些方法的事实:
input()函数:此函数按原样使用您输入的输入的值和类型,而无需修改其类型。
raw_input() 函数:此函数将您提供的输入明确转换为字符串类型,

注意:
input()方法的漏洞在于,任何人都可以使用变量或方法的名称来访问访问输入值的变量。

There are two ways to fix these issues,

  • 1st is simple without code change that is
    run your script by Python3,
    if you still want to run on python2 then after running your python script, when you are entering the input keep in mind

    1. if you want to enter string then just start typing down with “input goes with double-quote” and it will work in python2.7 and
    2. if you want to enter character then use the input with a single quote like ‘your input goes here’
    3. if you want to enter number not an issue you simply type the number
  • 2nd way is with code changes
    use the below import and run with any version of python

    1. from six.moves import input
    2. Use raw_input() function instead of input() function in your code with any import
    3. sanitise your code with str() function like str(input()) and then assign to any variable

As error implies:
name ‘dude’ is not defined i.e. for python ‘dude’ become variable here and it’s not having any value of python defined type assigned
so only its crying like baby so if we define a ‘dude’ variable and assign any value and pass to it, it will work but that’s not what we want as we don’t know what user will enter and moreover we want to capture the user input.

Fact about these method:
input() function: This function takes the value and type of the input you enter as it is without modifying it type.
raw_input() function: This function explicitly converts the input you give into type string,

Note:
The vulnerability in input() method lies in the fact that the variable accessing the value of input can be accessed by anyone just by using the name of variable or method.


回答 12

您可以更改在IDE中使用的python,如果您已经下载了python 3.x,则切换起来应该不太困难。但是您的脚本可以在python 3.x上正常工作,我只需要更改

print ("your name is" + input_variable)

print ("your name is", input_variable)

因为使用逗号,它会your name is在用户输入的内容与输入内容之间加上空格。AND:如果您使用的是2.7,请使用raw_input代替输入。

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

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 is and whatever the user inputted. AND: if you’re using 2.7 just use raw_input instead of input.