input(): “NameError: name 'n' is not defin

2020-01-29 02:45发布

问题:

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.

回答1:

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)).


回答2:

You are using the input() function on Python 2. Use raw_input() instead, or switch to Python 3.

input() runs eval() on the input given, so entering n is interpreted as python code, looking for the n variable. You could work around that by entering 'n' (so with quotes) but that is hardly a solution.

In Python 3, raw_input() has been renamed to input(), replacing the version from Python 2 altogether. If your materials (book, course notes, etc.) use input() in a manner that expects n to work, you probably need to switch to using Python 3 instead.