Your own while / else


Hi, I’m stuck on the excerise “Your own while / else”, could some one help me please? I don’t get any errors but something with my code is not correct.

Use a while loop to let the user keep guessing so long as guesses_left is greater than zero.

Ask the user for their guess, just like the second example above.

If they guess correctly, print “You win!” and break.

Decrement guesses_left by one.

Use an else: case after your while loop to print “You lose.”.

Error I get:

My code:

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)

guesses_left = 3
# Start your game!
while guesses_left > 0:
  guess = int(raw_input("Your guess:"))
  if guesses_left == random_number:
    print "You win!"
    guesses_left -= 1
      print "You lose."


the guess is only decreased if the user guesses the correct number, the guess should always be decreased

you currently have a if/else, not a while/else, by placing the else at same indent level as while, you get a while/else, then else will run when the loop condition evaluates to false, else doesn’t run when the loop breaks


Hi, so we want me to change the if in if guess == random_number: to a else and put it on the same indent level as while?


the if statement is fine, you need to change the indent level of else

you also need to ensure the number of guesses left is decreased by one every time. Currently, this only happens when the user guesses the random number, this is because the line of code that reduces the guesses by one is nested inside the if clause.


Thank you for the help


Why not have the “guesses_left -= 1” happen before the if statement? Seems to do the same thing?


This has my ears twitching since I cannot understand it.


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