8. While/else


#1



My error message: Oops, try again. Did you include an else for the while loop?

Who knows what is the mistake?


from random import randint

random_number = randint(1, 10)
guesses_left = 3

while guesses_left > 0:
    guess = int(raw_input('Your guess: '))
    if guess == random_number:
        print 'You win!'
        break
    else:
        print 'You lose.'
        guesses_left -= 1


#2

Remove the statement where you subtract one from guesses_left to your first if- statement after the break. Also your else- statement is in the wrong indentation level so remove one indent before it.


#3

Take a look at the indentation level of else. It is on the same level as the if, it means that this else is assigned to the if, not to the while loop.

You should decrement value of guesses_left when the user makes a guess.

Take a look at this corrected code:

from random import randint

random_number = randint(1, 10)
guesses_left = 3

while guesses_left > 0:
    guess = int(raw_input('Your guess: '))
    if guess == random_number:
        print 'You win!'
        break
    guesses_left -= 1
else:
    print 'You lose.'

If the user does not have any left guesses and user didn't win the then block of else will be executed.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.