突破while循环


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 shoppingListn')
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

我想在客户选择其中一个选项后打破循环

您似乎有布尔值openMenu,而while循环仅在openMenu = True时输入。

因此,解决此问题的一种方法是在每个条件语句之后设置openMenu = False

你会有:

openMenu = True
while openMenu:
costumerPick = input('Please choose item from the shoppingListn')
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 shoppingListn')
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

最新更新