“for”和列表问题

时间:2017-04-25 15:00:13

标签: python python-3.x python-3.6

我正在尝试使用用户输入传递信息并使用for循环。我一直得到一个IndexError:列表赋值索引超出范围

我希望它打印并让用户输入每个项目,然后询问信息是否正确,如果没有返回它们。但是,在尝试多种方法后,我无法得到正确的陈述。谢谢。

address = []
address_info = ('Name:', 'Address:', 'City:', 'State', 'Zip Code')

print('***DELIVERY METHOD***')
print('Please enter the info below from customer...')
for x in address_info:
    address[x] = input(address_info[x])
    x += 1

1 个答案:

答案 0 :(得分:-1)

尝试使用append-logic而不是使用索引。

address = []
address_info = ('Name:', 'Address:', 'City:', 'State', 'Zip Code')

print('***DELIVERY METHOD***')
print('Please enter the info below from customer...')

for info in address_info:     # these are the values not indicies
    user_input = input(info)
    address.append(user_input)

原始代码中存在问题。首先,for循环将循环来自 address_info 的值而不是指标。其次,结果列表需要通过追加来增长;在列表已经在可以替换的位置具有某个值之前,您无法进行索引分配。