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
4

2 回答 2

8

您正在使用input而不是raw_input使用 python 2,它将输入评估为 python 代码。

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

input()相当于eval(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!")
于 2013-04-28T17:38:17.203 回答
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 = 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'>

类似于使用intin input,使用它像:

>>> 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'>
于 2014-05-01T12:39:23.347 回答