4 回答

TA贡献1850条经验 获得超11个赞
您的代码有点难以阅读且难以维护我建议,当您想退出时将“while 循环”更改为无限循环,只需打破循环,我更喜欢在询问选项之前显示菜单。
您可以像这样更改代码:
def display_menu():
print("1. Add a new item to shopping list")
print("2. Remove an item")
print("3. Print Shopping List Items")
print("0. Exit")
return int(input('Enter an Options (0~3):'))
while True:
option = display_menu()
if option == 1:
item = input('enter the item : ')
qnty = int(input('Enter the Quantitiy for the item : '))
Shoping_list[item] = qnty
elif option == 2:
for item in Shoping_list:
print(item, ':', Shoping_list[item])
item = input('Enter the item you want to Remove : ')
del(Shoping_list[item])
elif option == 3:
for item in Shoping_list:
print(item, ':', Shoping_list[item])
elif option == 0:
print('shopping list is close')
break # Exit menu
else:
print('you didnt enter a valid number ')

TA贡献1824条经验 获得超6个赞
太棒了,非常感谢你们!我是 python 的新手,这个信息非常有帮助
def display_menu():
print("1. Add a new item to shopping list")
print("2. Remove an item")
print("3. Print Shopping List Items")
print("0. Exit")
return int(input('Enter an Options (0~3):'))
while True:
option = display_menu()
if option == 1:
item = input('enter the item : ')
qnty = int(input('Enter the Quantitiy for the item : '))
Shoping_list[item] = qnty
elif option == 2:
for item in Shoping_list:
print(item, ':', Shoping_list[item])
item = input('Enter the item you want to Remove : ')
del(Shoping_list[item])
elif option == 3:
for item in Shoping_list:
print(item, ':', Shoping_list[item])
elif option == 0:
print('shopping list is close')
break # Exit menu
else:
print('you didnt enter a valid number ')
Ps喜欢带有您可以调用的功能的选项

TA贡献1829条经验 获得超6个赞
在每个 if 语句中,在末尾插入 Options = 0。由于您的 while 循环取决于不为 0 的选项。将其重置为 0 允许用户选择另一个选项。
while Options != 0:
if Options == 1:
item = input('enter the item : ')
qnty = int(input('Enter the Quantitiy for the item : '))
Shoping_list[item] = qnty
Options = 0
另外,作为提示,请确保您的拼写和语法准确无误,并且间距保持一致。它使其他人更容易阅读您的代码。
这是正确的 if 循环的工作示例。用户可以用 if 循环修改字典,并且可以一个接一个地运行它们。
Shoping_list = {}
while True:
Options = int(input('Enter an Options :'))
while Options != 0:
if Options == 1:
item = input('enter the item : ')
qnty = int(input('Enter the Quantitiy for the item : '))
Shoping_list[item] = qnty
Options = 0
elif Options == 2:
for item in Shoping_list:
print(item, ':', Shoping_list[item])
item = input('Enter the item you want to Remove : ')
del(Shoping_list[item])
Options = 0
elif Options == 3:
for item in Shoping_list:
print(item, ':', Shoping_list[item])
Options = 0
elif Options != 0:
print('you didnt enter a valid number ')
else:
print('shopping list is close')

TA贡献1895条经验 获得超7个赞
Options = int(input('Enter an option'))在 while 循环中插入第一条语句。
while options!=0:
Options = int(input('Enter an option'))
.
.
.
.
- 4 回答
- 0 关注
- 127 浏览
添加回答
举报