python - 跳出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 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
我想在客户选择这些选项之一后打破循环
解决方案
似乎您有布尔值openMenu
,并且仅在 if 中输入了 while 循环openMenu = True
。
因此,解决此问题的一种方法是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 中的所有元素。
推荐阅读
- php - 如何从 composer.json 安装单个特定包以安装开发人员工具?
- mysql - Mysql将数据从一列复制到另一列并修改
- javascript - 切换文本打开时如何停止页面滚动?
- google-chrome - 如何让 Chrome 接受来自我的 .NET 应用程序的下载?
- python - 列表不会第二次加入,但会第一次加入
- php - 通过 PHP 获取 Google Streetview 标题
- c - 打印随机数到列表
- javascript - 向超链接添加功能
- api - 我可以在成功持久化数据之前发送 API 响应吗?
- javascript - 通过类名获取 div 内的嵌套元素