NameError when using input()

2019-01-12 10:36发布

So what am I doing wrong here?

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

However, I only get

  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条回答
爷、活的狠高调
2楼-- · 2019-01-12 11:14

Why are you using int and expecting string on input.?use raw_input for your case, it captures every possible values of answer as string. so in your case it would be something like this:

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

if you are using only input. expect 'answer' or "answer" for string. like:

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

similarly to use int in input, Use it like:

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

But if you type:

>>> 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'>
查看更多
smile是对你的礼貌
3楼-- · 2019-01-12 11:19

You are using input instead of raw_input with python 2, which evaluates the input as python code.

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

input() is equivalent to eval(raw_input())

Also you are trying to convert "Beaker" to an integer, which doesn't make much sense.

 

You can substitute the input in your head like so, with raw_input:

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

And with input:

answer = Beaker        # raises NameError, there's no variable named Beaker
if answer == "Beaker":
   print("Correct!")
查看更多
登录 后发表回答