input():“NameError:name'n'未定义”

时间:2013-07-01 20:53:17

标签: python terminal nameerror

好的,所以我在python中编写成绩检查代码,我的代码是:

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

当我通过我的python编译器运行它并选择"n"时,我收到一条错误消息:

  

“NameError:名称'n'未定义”

当我选择"y"时,我会得到另一个问题NameError的{​​{1}},但当我执行其他操作时,代码会正常运行。

非常感谢任何帮助,

谢谢。

2 个答案:

答案 0 :(得分:18)

在Python 2中使用raw_input获取字符串,Python 2中的input相当于eval(raw_input)

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

因此,当您在n中输入input之类的内容时,它认为您正在寻找名为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效果很好:

>>> raw_input()
n
'n'

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.

input上的帮助:

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

Equivalent to eval(raw_input(prompt)).

答案 1 :(得分:2)

您在Python 2上使用input() function。请改用raw_input()或切换到Python 3。

input()对给定的输入运行eval(),因此输入n将被解释为python代码,查找n变量。您可以通过输入'n'(使用引号)来解决这个问题,但这不是一个解决方案。

在Python 3中,raw_input()已重命名为input(),完全取代了Python 2中的版本。如果您的材料(书籍,课程笔记等)以期望input()起作用的方式使用n,则可能需要切换到使用Python 3。

相关问题