我正在使用列表来存储一些值。
示例代码:
for i in range(3):
print i
lst[i] = i+1
print lst[i]
但是我收到这样的错误:
lst[i] = i+1
NameError: name 'lst' is not defined
Python中数组需要初始化吗?我的代码有什么问题?
最佳答案
这是您的代码:
for i in range(3):
print i
lst[i] = i+1
print lst[i]
有两个问题
1- you havn't initialize your list, the computer doesn't know yet that you are working with a list (like you do in programs where u keep track of a counter variable like count = count + i because it must have a seed value to start with)
2- you cannot append elements to a list with the assignment operator, use the append function for that.
所以这是正确的代码:
lst = []
for i in range(3):
print(i)
lst.append(i+1)
print(lst[i])
输出: 0 1 2 3
关于python - python 错误: name '...' is not defined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24360277/