input():“名称错误:未定义名称'n'”

2024-04-27 20:30:52 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我正在用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: name 'n' is not defined"

当我选择"y"时,我会得到另一个NameError问题是'y',但是当我做其他事情时,代码会正常运行。

非常感谢您的帮助

谢谢你。


Tags: 代码youinputyourhavenotunitprint
2条回答

您正在Python 2上使用^{} function。请改用^{},或者切换到Python 3。

input()对给定的输入运行eval(),因此输入n被解释为python代码,查找n变量。你可以通过输入'n'(所以用引号)来解决这个问题,但这很难解决。

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

使用Python 2中的^{}来获取字符串,python2中的^{}相当于eval(raw_input)

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

所以,当你在input中输入类似n的内容时,它会认为你在寻找一个名为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)).

相关问题 更多 >