【问题标题】:NameError when using input() [duplicate]使用 input() 时出现 NameError [重复]
【发布时间】:2013-04-28 17:37:03
【问题描述】:

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

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

【问题讨论】:

  • 您正在使用int 并且您期待string?试试这个int("5") 和这个int("hello")

标签: python input python-2.7


【解决方案1】:

您在 python 2 中使用 input 而不是 raw_input,它将输入评估为 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!")

【讨论】:

    【解决方案2】:

    您为什么要使用 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'>
    

    类似于在input 中使用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 '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-07-09
      • 2015-09-22
      • 1970-01-01
      • 1970-01-01
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      相关资源
      最近更新 更多