Your own while else


#1

Hi,
I'm trying to understand what is going on here, just fishing for an explanation, I'd be most grateful for any.

the following code doesn't work when the else is inside (indented aligned with) the while loop; it gives the user infinite tries. It works if you win the game (and I can go to the next scree nonethewiser what's going on!):

But if the the else is (indented aligned) within the if loop, the game works as it should but, of course, the program throws a Try again. Did you include an else for the while loop?
My guess is that my counter is in teh wrong place or badly formated but I can't work it out!

from random import randint

random_number = randint(1, 10)
print random_number

guesses_left = 3

while guesses_left > 0:
guess = int(input("Your guesses: "))
if guess == random_number:
print "You Win!"
break
else:
print "You loose!"
guesses_left -=1

Any ideas?
Many thanks


#2

OK, I did some progress"
the
guesses_left-=1
right after
guess = int(raw_input("Your guesses: "))
and that and correcting the spelling mistake in lose works!
that's it unless you win! Then you get: Oops, try again. Did you print the "You lose." message?
(correction: after a few trials, sometimes wining also accepts the code, but most times it doesn't. Bonkers.)

What's going on?


#3

I think this is a bug of some sort. I was just coming to post about this to see if anyone else has run into the same issues. Pretty much if I win with my code, it says there is an error.


#4

How about something like this? (There might be a better, more Pythonic way):

from random import randint

random_number = randint(1, 10)
print random_number

guesses_left = 3
while guesses_left > 0:
    guess = int(raw_input("Your guesses: "))
    if guess == random_number:
        print "You Win!"
        break
    else:
        guesses_left -=1
if guesses_left == 0:
    print "You lose!"

This way it leaves the "while" loop after three guesses and then reconfirms outside the loop that they've lost.


#5