input():"NameError:名称'n'未定义" [英] input(): "NameError: name 'n' is not defined"

查看:159
本文介绍了input():"NameError:名称'n'未定义"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

当我通过python编译器运行它并选择"n"时,出现错误消息:

When I run it through my python compiler and I choose "n", I get an error saying:

"NameError:未定义名称'n'"

"NameError: name 'n' is not defined"

,当我选择"y"时,我得到了另一个NameError,而'y'是问题所在,但是当我执行其他操作时,代码将正常运行.

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.

非常感谢您的帮助,

谢谢.

推荐答案

使用 NameError 在Python 2中获取字符串 input 等同于eval(raw_input).

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

因此,当您在input中输入类似n的内容时,它会认为您正在寻找名为n的变量:

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正常工作:

>>> raw_input()
n
'n'


关于raw_input的帮助:


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.

关于input的帮助:

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

Equivalent to eval(raw_input(prompt)).

这篇关于input():"NameError:名称'n'未定义"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆