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

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 3及以上版本

s = raw_input()

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

s = input()

其他回答

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

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()方法的漏洞在于 任何人都可以访问访问输入值的变量 只是通过使用变量或方法的名称。

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

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

Ex:'dude' -> correct

    dude -> not correct

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

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

from six.moves import input

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

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

你可以这样做:

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