[英]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.