[英]Breaking out of while loop
shoppingList = [('Carrot',2), ('Onion',1), ('Tomato',3)]
amountGiven = 12
for item, price in shoppingList:
openMenu = True
while openMenu:
costumerPick = input('Please choose item from the shoppingList\n')
if costumerPick == 'Carrot':
print('That would be: ${}'.format(price))
amountGiven = amountGiven - price
elif costumerPick == 'Onion':
print('That would be: ${}'.format(price))
amountGiven = amountGiven -price
elif costumerPick == 'Tomato':
print('That would be: ${}'.format(price))
amountGiven = amountGiven - price
我想在客戶選擇其中一個選項后打破循環
看來您有 boolean openMenu
並且只有在openMenu = True
時才進入 while 循環。
因此,解決這個問題的一種方法是在每個條件語句之后設置openMenu = False
。
你將會擁有:
openMenu = True
while openMenu:
costumerPick = input('Please choose item from the shoppingList\n')
if costumerPick == 'Carrot':
print('That would be: ${}'.format(price))
amountGiven = amountGiven - price
openMenu = False
elif costumerPick == 'Onion':
print('That would be: ${}'.format(price))
amountGiven = amountGiven -price
openMenu = False
elif costumerPick == 'Tomato':
print('That would be: ${}'.format(price))
amountGiven = amountGiven - price
openMenu = False
但是,您似乎並不真的需要 while 循環,因為您的 for 循環遍歷了 shoppingList 中的所有元素。
我真的不明白你的問題。 如果你想從 while 循環中中斷,當滿足特定條件時,使用'break'語句。
shoppingList = [('Carrot',2), ('Onion',1), ('Tomato',3)]
amountGiven = 12
for item, price in shoppingList:
openMenu = True
while openMenu:
costumerPick = input('Please choose item from the shoppingList\n')
if costumerPick == 'Carrot':
print('That would be: ${}'.format(price))
amountGiven = amountGiven - price
break
elif costumerPick == 'Onion':
print('That would be: ${}'.format(price))
amountGiven = amountGiven -price
break
elif costumerPick == 'Tomato':
print('That would be: ${}'.format(price))
amountGiven = amountGiven - price
break
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.