Python 名称错误在一个非常简单的程序中

2024-04-25 03:59:27 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

请注意,如果我使用python2.7并改用raw_input,那么这个程序运行得很好。你知道吗


Tags: 答案in程序列表forinputlinerange
1条回答
网友
1楼 · 发布于 2024-04-25 03:59:27

在python2中,input计算给定的字符串,而raw_input将只返回一个字符串。注意,在python3中,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

相关问题 更多 >