简体   繁体   English

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

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

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 Mac OS X 10.9.1 and I am using the Python Launcher app that came with the install of Python 3.3 to run the script.我正在运行 Mac OS X 10.9.1,我正在使用 Python 3.3 安装附带的 Python Launcher 应用程序来运行脚本。

TL;DR TL; 博士

input function in Python 2.7, evaluates whatever your enter, as a Python expression. Python 2.7 中的input函数,将您输入的任何内容作为 Python 表达式进行评估。 If you simply want to read strings, then use raw_input function in Python 2.7, which will not evaluate the read strings.如果你只是想读取字符串,那么在 Python 2.7 中使用raw_input函数,它不会评估读取的字符串。

If you are using Python 3.x, raw_input has been renamed to input .如果您使用的是 Python 3.x, raw_input已重命名为input Quoting the Python 3.0 release notes ,引用Python 3.0 发行说明

raw_input() was renamed to input() . raw_input()被重命名为input() That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped.也就是说,新的input()函数从sys.stdin读取一行并返回它,并去掉尾部的换行符。 It raises EOFError if the input is terminated prematurely.如果输入过早终止,则会引发EOFError To get the old behavior of input() , use eval(input())要获得input()的旧行为,请使用eval(input())


In Python 2.7 , there are two functions which can be used to accept user inputs.在 Python 2.7 中,有两个函数可用于接受用户输入。 One is input and the other one israw_input .一个是input ,另一个是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. input接受来自用户的字符串并评估当前 Python 上下文中的字符串。 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 .当我输入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 os module in your program with import os , and then the user types in例如,如果您已经在程序中使用import os加载了os模块,然后用户输入

os.remove("/etc/hosts")

this will be evaluated as a function call expression by python and it will be executed.这将被python评估为函数调用表达式,并将被执行。 If you are executing Python with elevated privileges, /etc/hosts file will be deleted.如果您使用提升的权限执行 Python, /etc/hosts文件将被删除。 See, how dangerous it could be?看,这有多危险?

To demonstrate this, let's try to execute input function 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.现在,当input("Enter your name: ")被执行时,它等待用户输入并且用户输入是一个有效的 Python 函数调用,所以它也会被调用。 That is why we are seeing Enter your name again: prompt again.这就是为什么我们会看到Enter your name again:再次提示。

So, you are better off with raw_input function, 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 .如果需要将结果转换为其他类型,则可以使用适当的函数来转换raw_input返回的字符串。 For example, to read inputs as integers, use the int function, like shown in this answer .例如,要将输入读取为整数,请使用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

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)

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.它将默认为 Python 2.x。 These go on the first line of your script, if there is nothing that starts with #!如果没有以#! (aka the shebang). (又名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 的机器上运行。

I also encountered this issue with a module that was supposed to be compatible for python 2.7 and 3.7我也遇到了一个应该与 python 2.7 和 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您可以在此处阅读有关六个图书馆的更多信息

You should use raw_input because you are using python-2.7.您应该使用raw_input因为您使用的是 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.当您在变量上使用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))

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

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: "))

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

To determine whether or not your file is executable:要确定您的文件是否可执行:

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

If you've included import sys; print(sys.version)如果你已经包含了import sys; print(sys.version) 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)正如凯文建议的那样,你现在会看到脚本正在被python3解释

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

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'>)
Hi Joe, bye 

Your name: Joe
Joe

Thanks!谢谢!

There are two ways to fix these issues,有两种方法可以解决这些问题,

  • 1st is simple without code change that is第一个很简单,无需更改代码
    run your script by Python3,通过 Python3 运行您的脚本,
    if you still want to run on python2 then after running your python script, when you are entering the input keep in mind如果你仍然想在 python2 上运行,那么在运行你的 python 脚本之后,当你输入输入时请记住

    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如果你想输入string那么只需开始输入“输入带有双引号”,它就可以在 python2.7 和
    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使用以下导入并与任何版本的 python 一起运行

    1. from six.moves import input
    2. Use raw_input() function instead of input() function in your code with any import在任何导入的代码中使用raw_input()函数而不是input()函数
    3. sanitise your code with str() function like str(input()) and then assign to any variable使用str()函数(如str(input())清理您的代码,然后分配给任何变量

As error implies :正如错误所暗示的那样
name 'dude' is not defined ie for python 'dude' become variable here and it's not having any value of python defined type assigned名称 'dude' 未定义,即对于 python 'dude' 在这里变为变量,并且它没有分配任何 python 定义类型的值
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.所以只有它像婴儿一样哭泣所以如果我们定义一个“dude”变量并分配任何值并传递给它,它会起作用,但这不是我们想要的,因为我们不知道用户将输入什么,而且我们想要捕获用户输入。

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. input()函数:该函数采用您输入的输入的值和类型,而不修改它的类型。
raw_input() function: This function explicitly converts the input you give into type string, raw_input()函数:该函数将您提供的输入显式转换为字符串类型,

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. 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.您可以更改您在 IDE 中使用的 python,如果您已经下载了 python 3.x,切换应该不会太难。 But your script works fine on python 3.x, I would just change但是你的脚本在 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 is and whatever the user inputted.因为使用逗号,它会在your name is和用户输入的任何内容之间打印一个空格。 AND: if you're using 2.7 just use raw_input instead of input.并且:如果您使用的是 2.7,只需使用raw_input而不是 input。

Try using raw_input rather than input if you simply want to read strings.如果您只想读取字符串,请尝试使用raw_input而不是input

print("Enter your name: ")
x = raw_input()
print("Hello, "+x)

图像包含输出屏幕

Here is an input function which is compatible with both Python 2.7 and Python 3+: (Slightly modified answer by @Hardian) to avoid UnboundLocalError: local variable 'input' referenced before assignment error这是一个与 Python 2.7 和 Python 3+ 兼容的输入函数:(@Hardian 稍微修改了答案)以避免UnboundLocalError: local variable 'input' referenced before assignment错误UnboundLocalError: local variable 'input' referenced before assignment

def input_compatible(prompt=None):
    try:
        input_func = raw_input
    except NameError:
        input_func = input
    return input_func(prompt)

Also here is another alternative without a try block:这里还有另一种没有try块的替代方法:

def input_compatible(prompt=None):
    input_func = raw_input if "raw_input" in __builtins__.__dict__ else input
    return input_func(prompt)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM