与字典比较时,列表索引超出范围



我正试图使用字典变量和输入在Python 3.7中创建一个菜单系统,新的编码器只是在挠头

我试图将用户的选择保存在var选项中,然后使用选择与清除输入进行比较,但是当运行时,代码与一致失败

Traceback (most recent call last):
File "D:Nu Voute De Merde[Redact]Python Creations[Redact]code.py", line 32, in <module>
if choice == choices[5]:
IndexError: list index out of range

如有任何帮助,我们将不胜感激!代码:

from sys import exit
## Creates the menu using dict vars
menu = {}
menu['1']="Add New Address"
menu['2']="Change Existing Address"
menu['3']="View All Addresses Where Last Name Starts With Letter"
menu['4']="List All Addresses"
menu['5']="Quit"
#Takes the input from the user
choice = int(input("""
1.Add New Address
2.Change Existing Address
3.View All Addresses Where Last Name Starts With Letter
4.List All Addresses
5.Quit
"""))
#Sets available options
choices = [1, 2, 3, 4, 5]

if choice == choices[1]:
print (menu['1'])
if choice == choices[2]:
print (menu['2'])
if choice == choices[3]:
print (menu['3'])
if choice == choices[4]:
print (menu['4'])
if choice == choices[5]:
print (menu['5'])
exit()
elif choice not in choices:
print (menu['5'])
exit()

在大多数编程语言中,数组是0-indexed,因此

choices = [1, 2, 3, 4, 5]
print(choices[0]) # 1
print(choices[4]) # 5
print(choices[5]) # IndexError

dict的改进

  • 不需要将输入转换为int,您可以直接将输入的字符串与数组中的字符串进行比较

  • 你最好直接使用字典属性,来检查密钥的存在,避免了多次写相同的东西

  • 您可以使用dict内容在input中构建命题

## Creates the menu using dict vars
menu = {'1': "Add New Address",
'2': "Change Existing Address",
'3': "View All Addresses Where Last Name Starts With Letter",
'4': "List All Addresses",
'5': "Quit"}
# Takes the input from the user
choice = input("n".join('.'.join(pair) for pair in menu.items()) + "nChoice: ")
if choice == '5' or choice not in menu:
print(menu['5'])
exit()
else:
print(menu[choice])

列表改进

当你使用数字作为密钥时,你甚至可以将你的选择存储在阵列中

menu = ["Add New Address",
"Change Existing Address",
"View All Addresses Where Last Name Starts With Letter",
"List All Addresses",
"Quit"]
choice = int(input("n".join(f"{idx + 1}.{ch}"
for idx, ch in enumerate(menu)) + "nChoice: "))
if choice > 4:
print(menu[4])
exit()
else:
print(menu[choice - 1])

最新更新