使用input()时出现NameError错误

3

那么我在这里做错了什么?

answer = int(input("What is the name of Dr. Bunsen Honeydew's assistant?"))
if answer == ("Beaker"):
    print("Correct!")
else:
    print("Incorrect! It is Beaker.")

然而,我只得到了
  Traceback (most recent call last):
  File "C:\Users\your pc\Desktop\JQuery\yay.py", line 2, in <module>
    answer = int(input("What is the name of Dr. Bunsen Honeydew's assistant?"))
  File "<string>", line 1, in <module>
      NameError: name 'Beaker' is not defined

你正在使用 int,但期望得到一个 string?尝试使用 int("5")int("hello") - Abdelouahab Pp
2个回答

8

您在使用Python 2时,使用了input而非raw_input,这将会将输入的内容作为Python代码进行求值。

answer = raw_input("What is the name of Dr. Bunsen Honeydew's assistant?")
if answer == "Beaker":
   print("Correct!")

input()相当于eval(raw_input())

  • input:读取用户输入并尝试将其解析为Python表达式,然后返回结果。
  • raw_input:从标准输入读取一行,并在字符串末尾删除换行符。

另外,您正在尝试将“Beaker”转换为整数,这没有太多意义。

 

可以用raw_input在头脑中替换输入:

answer = "Beaker"
if answer == "Beaker":
   print("Correct!")

使用 input

answer = Beaker        # raises NameError, there's no variable named Beaker
if answer == "Beaker":
   print("Correct!")

0
为什么你在使用 int,但期望输入字符串?对于你的情况,请使用 raw_input,它可以捕获 answer 的任何可能值作为字符串。因此,在你的情况下,代码应该是这样的:
answer = raw_input("What is the name of Dr. Bunsen Honeydew's assistant?")
#This works fine and converts every input to string.
if answer == 'Beaker':
   print ('Correct')

如果你只使用 input。期望字符串的 'answer' 或 "answer"。例如:

>>> answer = input("What is the name of Dr. Bunsen Honeydew's assistant?")
What is the name of Dr. Bunsen Honeydew's assistant?'Beaker'#or"Beaker"
>>> print answer
Beaker
>>> type(answer)
<type 'str'>

类似于在输入中使用int,使用方式如下:
>>> answer = input("What is the name of Dr. Bunsen Honeydew's assistant?")
What is the name of Dr. Bunsen Honeydew's assistant?12
>>> type(answer)
<type 'int'>

但是如果你输入:

>>> answer = input("What is the name of Dr. Bunsen Honeydew's assistant?")
What is the name of Dr. Bunsen Honeydew's assistant?"12"
>>> type(answer)
<type 'str'>
>>> a = int(answer)
>>> type(a)
<type 'int'>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接