使用 input() 时出现 NameError [英] NameError when using input()

查看:17
本文介绍了使用 input() 时出现 NameError的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.")

然而,我只得到

  Traceback (most recent call last):
  File "C:Usersyour pcDesktopJQueryyay.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

推荐答案

您在 python 2 中使用 input 而不是 raw_input,python 2 将输入计算为 python 代码.

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() 等价于 eval(raw_input())

您还试图将Beaker"转换为整数,这没有多大意义.

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

 

你可以像这样用raw_input替代你头脑中的输入:

You can substitute the input in your head like so, with 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!")

这篇关于使用 input() 时出现 NameError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆