【问题标题】:Python: NameError in a very simple program [duplicate]Python:一个非常简单的程序中的NameError [重复]
【发布时间】:2014-01-22 20:06:43
【问题描述】:

我正在使用 for 循环制作一个使用 for 循环的超级简单的程序,该程序会询问您 3 次您的爱好并将您的答案附加到一个名为 hobbies 的列表中:

hobbies = []

for me in range(3):
    hobby=input("Tell me one of your hobbies: ")
    hobbies.append(hobby)

例如,如果我给它“编码”,它将返回:

Traceback (most recent call last):
  File "python", line 4, in <module>
  File "<string>", line 1, in <module>
NameError: name 'coding' is not defined

请注意,如果我使用 Python 2.7 并改用 raw_input,则程序运行良好。

【问题讨论】:

    标签: python list for-loop append nameerror


    【解决方案1】:

    在 Python 2 中,input评估给定的字符串,而raw_input 将只返回一个字符串。请注意,在 Python 3 中,raw_input 被重命名为 input,而旧的 input 仅以 eval(input()) 的形式提供。

    Python 2 中的示例:

    In [1]: x = 2
    
    # just a value
    In [2]: x ** input("exp: ")
    exp: 8
    Out[2]: 256
    
    # refering to some name within
    In [3]: x ** input("exp: ")
    exp: x
    Out[3]: 4
    
    # just a function
    In [4]: def f():
       ...:     print('Hello from f')
       ...:
    
    # can trigger anything from the outside, super unsafe
    In [5]: input("prompt: ")
    prompt: f()
    Hello from f
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-03-04
      • 2018-03-15
      • 2017-09-03
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 2021-12-02
      相关资源
      最近更新 更多