“for”和列表的问题

2024-10-06 06:26:53 发布

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

我试图让用户输入传递信息并使用for循环。我不断得到一个索引错误:列表分配索引超出范围

我想它打印出来,让用户输入每个项目,然后询问信息是否正确,如果没有返回他们。但是,在尝试了多种方法之后,我无法获得正确的语句。非常感谢。你知道吗

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

Tags: 项目方法用户nameinfo信息列表for
1条回答
网友
1楼 · 发布于 2024-10-06 06:26:53

尝试使用附加逻辑而不是索引。你知道吗

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\u info的值,而不是指示符。第二,结果列表需要通过追加来增长;在列表的可替换位置上已有值之前,不能进行索引赋值。你知道吗

相关问题 更多 >