input(): “NameError: name ‘n’ is not defined” [duplicate]

Use raw_input in Python 2 to get a string, input in Python 2 is equivalent to eval(raw_input).

>>> type(raw_input())
23
<type 'str'>
>>> type(input())
12
<type 'int'>

So, When you enter something like n in input it thinks that you’re looking for a variable named n:

>>> input()
n
Traceback (most recent call last):
  File "<ipython-input-30-5c7a218085ef>", line 1, in <module>
    type(input())
  File "<string>", line 1, in <module>
NameError: name 'n' is not defined

raw_input works fine:

>>> raw_input()
n
'n'

help on raw_input:

>>> print raw_input.__doc__
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.

help on input:

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

Equivalent to eval(raw_input(prompt)).

Leave a Comment