首页 > 解决方案 > 当用户在 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。我该如何进行这项工作?

标签: python

解决方案


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!!!")

推荐阅读