使用input()时的NameError

时间:2013-04-28 17:37:04

标签: python input python-2.7

那我在这里做错了什么?

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

2 个答案:

答案 0 :(得分: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!")

答案 1 :(得分: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')

OR

如果您仅使用input。期待&#39;回答&#39;或者&#34;回答&#34;对于字符串。像:

>>> 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'>