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

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

问题描述

好的,所以我正在用 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).

<预><代码>>>>类型(原始输入())23<输入'str'>>>>类型(输入())12<输入'int'>

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

<预><代码>>>>输入()n回溯(最近一次调用最后一次):文件<ipython-input-30-5c7a218085ef>",第 1 行,在 <module> 中类型(输入())文件<string>",第 1 行,在 <module> 中NameError: 名称 'n' 未定义

raw_input 工作正常:

<预><代码>>>>原始输入()n'n'

<小时>

raw_input 的帮助:

<预><代码>>>>打印 raw_input.__doc__原始输入([提示])->细绳从标准输入读取字符串.尾部的换行符被删除.如果用户点击 EOF(Unix:Ctl-D,Windows:Ctl-Z+Return),则引发 EOFError.在 Unix 上,如果启用,则使用 GNU readline.提示字符串,如果给定,在阅读之前没有尾随换行符打印.

关于输入的帮助:

<预><代码>>>>打印输入.__doc__输入([提示])->价值相当于 eval(raw_input(prompt)).

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屋!

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