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

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


当前回答

前几篇贡献不错。

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

谢谢!

其他回答

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

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

Ex:'dude' -> correct

    dude -> not correct

你可以这样做:

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

前几篇贡献不错。

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

谢谢!

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

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

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

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