0

I'm a C programmer, and started with python today, just for a test, I throw some very simple code, and I get this very crazy nameError, I've saw a couple of then here, but they dont seem to relate.

person = input('Enter your name: ')

print('Hello', person)

This is what I get at the terminal:

C:\Users\Matt\Desktop\Python>python input.py
Enter your name: Matheus
Traceback (most recent call last):
File "input.py", line 3, in <module>
 person = input('Enter your name: ')
File "<string>", line 1, in <module>
NameError: name 'Matheus' is not defined

Does anybody knows how can I fix that?

  • 2
    Possible duplicate of [Python input() error - NameError: name '...' is not defined](http://stackoverflow.com/questions/21122540/python-input-error-nameerror-name-is-not-defined) – Yu Hao Nov 01 '15 at 00:59
  • in python2, use `raw_input` to input strings. `input` will attempt to evaluate the input as a python statement. – tdelaney Nov 01 '15 at 01:06

2 Answers2

0

Python 2 tries to interpret calls to input as code. Try raw_input() instead and it should work fine.

Randy
  • 14,349
  • 2
  • 36
  • 42
0

You are using Python 2, and in Python 2 the usage of input runs an eval on the input. So when you enter what you think is a string, Python tries to evaluate this.

From the help of input:

input(...)
    input([prompt]) -> value

    Equivalent to eval(raw_input(prompt)).

Demo of input:

>>> a = input()
2
>>> type(a)
<type 'int'>

Notice quotes have to be used to get the string:

>>> a = input()
"bob"
>>> type(a)
<type 'str'>

You are better off using raw_input in Python 2. As is this is even the method that is used in Python 3 (but Python 3 calls the method input).

raw_input(...)
    raw_input([prompt]) -> string

    Read a string from standard input.  The trailing newline is stripped.
    If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
    On Unix, GNU readline is used if enabled.  The prompt string, if given,
    is printed without a trailing newline before reading.

raw_input demo:

Notice quotes don't have to be used.

>>> a = raw_input()
bob
>>> type(a)
<type 'str'>
idjaw
  • 25,487
  • 7
  • 64
  • 83
  • 1
    Thanks, that was a nice explanation. I knew I was using the python 2.x but didnt know the my source was using python 3.x, thanks for the feedback, it solved the problem. – Matheus Alves Nov 01 '15 at 01:29