Search code examples
pythonqpython

'Name' is not defined, but I swear it is? (Python)


I'm testing out this QPython app on my phone and I have the following code:

#-*-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

However, it returns an error:

> 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:/ $

Sorry if formatting is off, I am posting this from my phone on the go.


Solution

  • You are using Python2, input() will evaluate input; which means when you type jason, it is trying to find a variable called jason, and since it doesn't exist, you get the exception. You should raw_input, which will return the input as a string:

    >>> 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'
    

    In Python3, it will work as expected:

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