'名字'没有定义,但我发誓它是? (蟒蛇)

时间:2014-10-02 20:50:31

标签: python qpython

我正在手机上测试这个QPython应用程序,我有以下代码:

#-*-coding:utf8;-*
#qpy:console
#qpy:2

numOne = 1
numTwo = 2

person = str(input("What's your name?")) 
print "Guess what I can do?" 
print "Hello,", person

但是,它会返回错误:

> hipipal.qpyplus/scripts/.last_tmp.py"    <
What's your name?jason
Traceback (most recent call last):
  File "/storage/emulated/0/com.hipipal.qpyplus/scripts/.last_tmp.py", line 8, in <module>
    person = str(input("What's your name?"))
  File "<string>", line 1, in <module>
NameError: name 'jason' is not defined
1|u0_a320@hltetmo:/ $

抱歉,如果格式化已关闭,我会在旅途中通过手机发布此信息。

1 个答案:

答案 0 :(得分:2)

您正在使用Python2,input()将评估输入;这意味着当您键入jason时,它会尝试查找名为jason的变量,并且由于它不存在,您将获得异常。您应raw_input,它将以字符串形式返回输入:

>>> input('hello: ')
hello: jason
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'jason' is not defined
>>> raw_input('hello: ')
hello: jason
'jason'

在Python3中,它将按预期工作:

>>> input('hello: ')
hello: json
'json'