输入():“NameError:名称'n'未定义"; [英] input(): "NameError: name 'n' is not defined"
问题描述
好的,所以我正在用 python 编写成绩检查代码,我的代码是:
unit3Done = str(input("你完成了你的第 3 单元控制评估吗?(输入 y 或 n):")).lower()如果 unit3Done == "y":经过elif unit3Done == "n":打印抱歉.您必须至少完成一个单元来计算 A* 所需的内容"别的:打印对不起.这不是一个有效的答案."
当我通过 python 编译器运行它并选择 "n"
时,我收到一条错误消息:
NameError: name 'n' 未定义"
当我选择 "y"
时,我得到另一个 NameError
与 'y'
的问题,但是当我做其他事情时,代码正常运行.
非常感谢任何帮助,
谢谢.
使用 <代码>raw_input 在 Python 2 中获取字符串,input
在 Python 2 中等价于 eval(raw_input)
.
因此,当您在 input
中输入类似 n
的内容时,它认为您正在寻找名为 n
的变量:
raw_input
工作正常:
<小时>
raw_input
的帮助:
关于输入
的帮助:
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.
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)).
这篇关于输入():“NameError:名称'n'未定义";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!