当我试图运行这个简单的脚本时,我得到一个错误:

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应用程序来运行脚本。


当前回答

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

输入时必须使用单引号或双引号

Ex:'dude' -> correct

    dude -> not correct

其他回答

下面是一个与Python 2.7和Python 3+兼容的输入函数: (稍微修改了@Hardian的回答)以避免UnboundLocalError:在赋值错误之前引用本地变量“input”

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

这里还有另一个没有try块的选项:

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

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

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 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 if you want to enter character then use the input with a single quote like 'your input goes here' 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 from six.moves import input Use raw_input() function instead of input() function in your code with any import sanitise your code with str() function like str(input()) and then assign to any variable

错误提示:name 'dude'没有定义 例如,对于python来说,'dude'在这里成为变量,它没有任何python定义的赋值类型,所以只有它像婴儿一样哭泣,所以如果我们定义一个'dude'变量,赋值并传递给它,它会工作,但这不是我们想要的,因为我们不知道用户将输入什么,而且我们想捕捉用户输入。

关于这些方法的事实: input()函数:这个函数接受你输入的值和类型,而不修改它的类型。raw_input () 这个函数显式地将输入转换为string类型, 注意:input()方法的漏洞在于 任何人都可以访问访问输入值的变量 只是通过使用变量或方法的名称。

我在使用一个应该兼容python 2.7和3.7的模块时也遇到了这个问题

我发现解决这个问题的方法是导入:

from six.moves import input

这修复了两个解释器的可用性

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

对于任何可能遇到这个问题的人来说,事实证明,即使您包含#!/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解释

我们正在使用以下代码,python 2和python 3都可以使用

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