Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

input(): "NameError: name 'n' is not defined" [duplicate]

Ok, so I'm writing a grade checking code in python and my code is:

unit3Done = str(input("Have you done your Unit 3 Controlled Assessment? (Type y or n): ")).lower()
if unit3Done == "y":
    pass
elif unit3Done == "n":
    print "Sorry. You must have done at least one unit to calculate what you need for an A*"
else:
    print "Sorry. That's not a valid answer."

When I run it through my python compiler and I choose "n", I get an error saying:

"NameError: name 'n' is not defined"

and when I choose "y" I get another NameError with 'y' being the problem, but when I do something else, the code runs as normal.

Any help is greatly appreciated,

Thank you.

like image 766
Cal Courtney Avatar asked Jul 01 '13 20:07

Cal Courtney


1 Answers

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)).
like image 159
Ashwini Chaudhary Avatar answered Sep 21 '22 01:09

Ashwini Chaudhary