所以我在做什么错在这里?
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
您使用的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())
你也正在试图“烧杯”转换为整数,这并没有太大的意义。
您可以替换输入你的脑袋像这样,用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!")
你为什么要使用int
和期待上input.?use字符串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'>
同样采用int
的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'>