Your own while / else


#1

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.

Instructions:
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:
111

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!"
    break
    guesses_left -= 1
  else:
      print "You lose."



#2

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


#3

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?


#4

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.


#5

Thank you for the help


#6

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


#7

This has my ears twitching since I cannot understand it.


#8

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