Python Forum

Full Version: How to fix while loop breaking off
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

So I was trying out a hangman game from this website and I have an issue that I can't seem to solve in other projects as well.

def play_loop():
    global play_game
    play_game = input("Do You want to play again? y = yes, n = no \n")
    while play_game not in ["y", "n","Y","N"]:
        play_game = input("Do You want to play again? y = yes, n = no \n")
    if play_game == "y":
        main()
    elif play_game == "n":
        print("Thanks For Playing! We expect you back again!")
        exit()
In the part here, when the game is over, it asks you if you want to play again, if you answer yes the program is over, if you say no the program exits (as it should) and if you answer with something else, it asks you again until you answer with either yes or no, though when you answer with yes, the program stops again.
There is no error or anything, the loop just breaks off I guess.

I played around with the code but I can't find the solution. I have had this problem before because of the same reason. If answer is yes, nothing happens.

Thank you for your help
Maybe try something like

#! /usr/bin/env python3

def play():
    while True:
        play_again = input('Play Again? ')
        if play_again.lower() in ['y', 'yes']:
            print('I am playing agin')
            # Do some stuff
        elif play_again.lower() in ['n', 'no']:
            print('Thanks for playing!')
            break
        else:
            print('Please type yes or no')
            continue

play()
Output:
Play Again? yes I am playing agin Play Again? mm Please type yes or no Play Again? no Thanks for playing!
Thank you. Yeah I get that much but exactly "Do some stuff" is what bugs me. I don't know what to write here so that it returns to the beginning of the game.
"Do some stuff" is where you call your function that plays the game.
def play_game():
    '''code for playing my game'''

while True:
    inp = input('Would you like to play my wonderful game? ')
    if len(inp) == 0 or inp[0].upper() != 'Y':
        break
    play_game()
This loop requires the user to input some kind of YES, Yes, yes, yup, y, Y to play otherwise it exits. If you want to play the game at least once you make a slight change.
def play_game():
    '''code for playing my game'''

while True:
    play_game()
    inp = input('Would you like to play my wonderful game? ')
    if len(inp) == 0 or inp[0].upper() != 'Y':
        break