python - 当用户在 Python 中输入 ''quit'' 时,中断循环并退出程序
问题描述
我在 Python 中有一个类似宾果游戏的工作代码(匹配全卡时宣布获胜者):
bingoCard = [7, 26, 40, 58, 73, 14, 22, 34, 55, 68]
while len(bingoCard) != 0:
nNumberCalled = int(input("\nPlease enter the announced Bingo Number: "))
if nNumberCalled <1 or nNumberCalled > 80:
print("Oops, the number should be between 1 and 80.")
elif nNumberCalled in bingoCard:
bingoCard.remove(nNumberCalled)
print(f"Nice on1e! You hit {nNumberCalled}.")
else:
print("Nah... Not in your card.")
print("\nBINGO!!!")
这个想法是我从bingoCard
它们中删除数字,直到列表为空。
我想通过键入“退出”随时为用户提供退出游戏(跳出循环)的选项。
我试图研究这个问题,但我无法弄清楚如何或在何处将break
语句添加到我的代码中以使其正常工作。我想我必须在循环中包含其他内容,例如try
/except
或者可能是for
循环while
。我该如何进行这项工作?
解决方案
while
接收输入,如果字符串是 ,然后从循环中跳出来quit
怎么样?如果输入不是quit
,则照常进行,即将输入解析为整数。
另请注意,您不想只调用break
,因为即使他/她退出,这也会让用户看到“BINGO”消息。为了解决这个问题,根据@JoeFerndz 的建议,while ... else
使用了子句。这个条款是我不知道的,我认为它非常有用。谢谢你的问题(当然还有@JoeFerndz 的评论),我可以从中学到新的东西!
bingoCard = [7, 26, 40, 58, 73, 14, 22, 34, 55, 68]
while len(bingoCard) != 0:
user_input = input("\nPlease enter the announced Bingo Number (or 'quit'): ")
if user_input.lower() == 'quit':
print("Okay bye!")
break
nNumberCalled = int(user_input)
if nNumberCalled <1 or nNumberCalled > 80:
print("Oops, the number should be between 1 and 80.")
elif nNumberCalled in bingoCard:
bingoCard.remove(nNumberCalled)
print(f"Nice on1e! You hit {nNumberCalled}.")
else:
print("Nah... Not in your card.")
else:
print("\nBINGO!!!")
推荐阅读
- python - Python - 正则表达式查找字符串并获取 x 字母 - 转义不起作用
- javascript - 使用 forEach 更新文档时出现“MongoExpiredSessionError:无法使用已结束的会话”,但为什么?
- r - 求解 R 中的复杂方程
- java - 来自 jsp 输入表单的错误编码
- html - 将图像的显示类型更改为“块”,使其下角变圆,如何?
- python - 如何随机化两次,而第二次与第一次不相交
- jmeter-plugins - 如何在没有互联网连接的 Windows 10 机器上安装 Taurus 框架?
- vue.js - 在 vuejs 中管理大型计算对象
- python - Flask 仅在 post api 获取数据时渲染 html
- javascript - 角度打印过滤列表