[8. Your own while / else] Why does one code work and the other does not?


#1



I have two questions:
1. Why does the game stop after the 1st round in the case of the second fragment of code I pasted, but not the frist?
2. Why is the else condition outside the if statement?


So this code apparently works:

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

This one however does not work (although the excercise is marked as correctly solved), because the game only runs one time.

from random import randint

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

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

#2

1) Put what you want to repeat in a loop
2) Have you read what the exercise is about?


#3

In both case you execute only once this part of loop:

while guesses_left  > 0:
    if random_number == guess:

Then it goes to print win/loss msg.
Consider what is part of loop.
and in second example you got also wrong indentation by else


#4

in while loop you have to kept like this

while guesses_left>0:
guess = int(raw_input("Your guess: ")