Home > Blockchain >  I'm trying to nest if statement inside a while loop
I'm trying to nest if statement inside a while loop

Time:07-19

I am building a hangman game as a beginner but i got stuck when i wanted the program to stop the loop if the number of correct guesses is equal to the length of the word. how do i stop the loop if the numbers are equal

here is the code:

    print (f'the first letter is {theww[0]}')
    chances = 5
    guesses = [theww[0]]
    newl = len(guesses)
    while chances != 0:
        choice = input ('Enter a word that you think is there: ')
        if choice in theww:
            print ('it is there')
            y = guesses.append(choice)
            print (guesses)
            if newl == length:
                print ('you won')
        elif choice not in theww:
            print ('not there')
            chances = chances - 1
        else:
            print('i think there was a problem, please start again')
            hangman()
    print('out of chances')

CodePudding user response:

Add a break right after you print you win.

Like this:

if newl == length:
    print ('you won')
    break

However, right now, when it breaks, it will print "out of chances" after "you win". To avoid this, put the "out of chances" in an else statement, similar to this:

    while chances != 0:
        choice = input ('Enter a word that you think is there: ')
        if choice in theww:
            print ('it is there')
            y = guesses.append(choice)
            print (guesses)
            if newl == length:
                print ('you won')
                break
        elif choice not in theww:
            print ('not there')
            chances = chances - 1
        else:
            print('i think there was a problem, please start again')
            hangman()
    else:
        print('out of chances')

The while/else makes sure that it will only print "out of chances" when the loop exits due to chances being 0. Check this article out for more info.

  • Related