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

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


当前回答

下面是一个与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)

其他回答

您正在运行Python 2,而不是Python 3。为了在Python 2中工作,使用raw_input。

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

你可以这样做:

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

对于python 3及以上版本

s = raw_input()

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

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

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

Ex:'dude' -> correct

    dude -> not correct

如果您只想读取字符串,请尝试使用raw_input而不是input。

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