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 關注
- 120 瀏覽
添加回答
舉報