8. your own while / else


#1




When ever I type in the number correctly incorrectly, it says that, "Did you include an else for the while loop?"


But, as you can see, I have an else under the if in my while loop, can someone help me?


from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)
print random_number
guesses_left = 3
# Start your game!
while guesses_left > 0:
    guess = int(raw_input("Your guess: \n"))
    guesses_left -=1
    if guess == random_number:
        print 'You win!'
        guesses_left = 0
        break
    
    else:
        print 'You lose'
        break


#2

@bytepro14871 ,

Does the indentation of your else header match it with the header of the while loop, or with something else?


#3

The else: statement must match the indentation of the while statement. So after both are aligned your issue should be fixed.


#4

I thought I had to have it aligned with the is, not the while statement.


#5

I tried it like this:

while guesses_left > 0:
    guess = int(raw_input("Your guess: \n"))
    guesses_left -=1
    if guess == random_number:
        print 'You win!'
        guesses_left = 0
        break
    
else:
    print 'You lose'
    break

and it said, "File "Python", line 18
SyntaxError: 'break' outside loop"


#6

Actually, you were right, I just had to remove the break statement.


#7

Hi, @bytepro14871,

In the Your own while / else exercise, the user associates an else block with the while loop block, so that if and when the condition specified in the while loop header ultimately becomes evaluated as False, the else block executes instead of the while loop block. However, if the user wins the game, the break in the if block contained in the while loop terminates the while loop. In that instance, the while condition does not get an opportunity to evaluate as False, and the else block does not execute.


#8

it a while/else, not an if/else. so the else should have same indentation level as the while and not the if


#9