# [solved] your own while else

#1

``````from random import randint
guesses_left = 0
while guesses_left < 3:
random_number = randint(1, 10)
if guess == random_number:
print "You win!"
break
guesses_left -= 1
else:
print "You lose."

guesses_left = 3

I've created a game where i always win.
Can someone explain, why is that?
The exercise tells me it's correct, but i know it's not.

#2

well, your loop will keep generating random numbers until it found a "random number" which equals your guess, then break is reached, the loop breaks

If the `break` wouldn't have been there, you would have yourself a infinity loop (take a good look at your code while otherwise you would have an infinity loop)

i would personally swap it, i would place `guess = int(raw_input("Your guess: "))` inside the loop so the user can have multiply guesses and place `random_number = randint(1, 10)` outside the loop so the random number is only generated once

#3

``````from random import randint
guesses_left = 3
random_number = randint(1, 10)
while guesses_left > 0:
if guess == random_number:
print "You win!"
break
guesses_left -= 1
else:
print "You lose."

guesses_left = 3

Ok, so i corrected the code like you suggested, and i understand why.
I also updated how many guesses does user have, and its correct 3,
but i get following error:
Oops, try again. Did you allow the user 3 guesses, or did you incorrectly detect a correct guess?

#4

your code is fine, that is the troubling bit. Here:

``````from random import randint
guesses_left = 3
random_number = randint(1, 10)
print random_number
while guesses_left > 0:
if guess == random_number:
print "You win!"
break
guesses_left -= 1
else:
print "You lose."

guesses_left = 3``````

this will print the random number, if you enter this you will get a pass, i don't see why the exercise throws an error, everything works fine

#5

Apparently it let's you pass only when you get the correct number, if you lose, you don't pass.
Strange.

#6

hm... not necessarily, i think the problem is actually here:

``````else:
print "You lose."

guesses_left = 3``````

you set guesses_left to three again at the end of your script, this will cause problems in the validation. If you remove your last line, you should be able to pass without guessing the correct number

#7

Thank you for your time and effort.
Brg

#8