Cal*_*ney 11 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."
Run Code Online (Sandbox Code Playgroud)
当我通过我的python编译器运行它并且我选择时"n",我得到一个错误说:
"NameError:名称'n'未定义"
当我选择"y"我再NameError有'y'是问题,但是当我做别的事情,代码运行正常.
任何帮助是极大的赞赏,
谢谢.
Ash*_*ary 18
使用raw_inputPython中2得到一个字符串,input在Python 2相当于eval(raw_input).
>>> type(raw_input())
23
<type 'str'>
>>> type(input())
12
<type 'int'>
Run Code Online (Sandbox Code Playgroud)
所以,当你进入像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
Run Code Online (Sandbox Code Playgroud)
raw_input 工作良好:
>>> raw_input()
n
'n'
Run Code Online (Sandbox Code Playgroud)
帮助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.
Run Code Online (Sandbox Code Playgroud)
帮助input:
>>> print input.__doc__
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
Run Code Online (Sandbox Code Playgroud)
您正在Python 2 上使用该input()函数。请raw_input()改用,或切换到 Python 3。
input()eval()在给定的输入上运行,因此输入n被解释为 python 代码,寻找n变量。您可以通过输入'n'(用引号引起来)来解决这个问题,但这几乎不是解决方案。
在 Python 3 中,raw_input()已重命名为input(),完全替换了 Python 2 中的版本。如果您的材料(书籍、课程笔记等)input()以预期n有效的方式使用,您可能需要改用 Python 3。