简体   繁体   English

当用户在 Python 中键入“退出”时,中断循环并退出程序

[英]Break a loop and quit the program when user types ''quit'' in Python

I have this working code for a bingo-like game in Python (a winner is announced when the full card is matched):我在 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!!!")

The idea is that I remove numbers from the bingoCard as they are called, until the list is empty.这个想法是我从bingoCard中删除被调用的数字,直到列表为空。

I would like to give to the user the option to quit the game (break out of the loop) at any time by typing "quit".我想通过键入“退出”随时为用户提供退出游戏(跳出循环)的选项。

I tried to research this question, but I couldn't figure out how or where to add a break statement into my code to make it work correctly.我试图研究这个问题,但我无法弄清楚如何或在何处将break语句添加到我的代码中以使其正常工作。 I guess I have to include something else such as try / except or maybe a for loop inside the while loop.我想我必须在while循环中包含其他内容,例如try / except或者for循环。 How do I make this work?我该如何进行这项工作?

How about receiving the input, and then breaking out from the while loop if the string is quit ?如果字符串quit ,接收输入,然后从while循环中跳出怎么样? If the input is not quit , then proceed as you did, ie, parse the input as integer.如果输入不是quit ,则照常进行,即将输入解析为 integer。

Also note that you wouldn't want to just invoke break , because that would let the user see "BINGO" message even if he/she quits.另请注意,您不想只调用break ,因为即使他/她退出,这也会让用户看到“BINGO”消息。 To address this issue, as per a suggestion by @JoeFerndz, while... else clause is used.为了解决这个问题,根据@JoeFerndz 的建议,使用了while... else子句。 This clause is what I was not aware of, and I think it is very useful.这个条款是我不知道的,我认为它非常有用。 Thank you for the question (and of course @JoeFerndz as well for the comment), from which I could learn something new!谢谢你的问题(当然还有@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!!!")

First make a list of quits and put a break at proper place like this:首先列出一个退出列表,然后在适当的地方break一下,如下所示:

bingoCard = [7, 26, 40, 58, 73, 14, 22, 34, 55, 68]

while len(bingoCard) != 0:
    new_var = input("\nPlease enter the announced Bingo Number: ")
    if(new_var in ['quit', 'Quit', 'QUIT']):
        break
    else:
        nNumberCalled = int(new_var)
        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!!!")

Could give this a try:可以试试这个:

bingoCard = [7, 26, 40, 58, 73, 14, 22, 34, 55, 68]
ch=''
while ch!='q':
    nNumberCalled = int(input("Please 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("Nice on1e! You hit ",nNumberCalled)
    else:
        print("Nah... Not in your card.")
    if len(bingoCard) == 0:
        break
    ch = input("Press q to quit or any other key to continue: ")

if(ch=='q'):
    print("Thank You")
else:
    print("\nBINGO!!!")

What I am doing is, keeping a variable to get the choice of the user in every iteration.我正在做的是,保留一个变量以在每次迭代中获得用户的选择。 If the user enters 'q', the code breaks out of the loop and checks for the last user input, else the game continues.如果用户输入'q',代码会跳出循环并检查最后的用户输入,否则游戏继续。 Outside the loop, if it is found that the last user choice was 'q', it means that the user has quit the game, otherwise it prints BINGO.在循环外,如果发现用户最后选择的是'q',则表示用户退出游戏,否则打印BINGO。 Please note, the other way of breaking out of the loop is when you have guessed all the numbers on your card.请注意,另一种跳出循环的方法是当您猜到卡上的所有数字时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM