input():“ NameError:未定义名称'n'”
好的,所以我正在用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
有'y'
是问题,但是当我做别的事情,代码运行正常。
任何帮助是极大的赞赏,
谢谢。
-
raw_input
在Python
2中使用来获取字符串,input
在Python
2中等效于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)).