Continuing the discussion from 8. Your own while/else:

Maybe I'm confused, but why is the "else" statement indented WITH the "while" statement instead of INSIDE the "while" statement? Did I miss something?


Hey post your code so we can take a look :slight_smile:


Why did you withdraw your post? :hushed:


It's not formatting correctly, but it's the same code in both instances, the only changes being the indentation of the "else" statement. In the first one, I indent "else", and codecademy tells me to include an "else" statement. In the second instance, I don't indent "else" and the program seems to let me guess until I get it right.

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



Well to answer your indentation dilemma. Indentation is a big part in programming but especially in loops. Because with while loops or any other loop for that matter. If/else or return statements communicate to python what you want to do before the loop stops It is actually not advisable to have incorrect indentation purposely when dealing with while loops because the risk of creating an infinite loop is higher. When else or return statement is not indented to the same level as the loop statement python does'nt know what to do after the loop's condition is met thus resulting in an unfinished loop or error message. :slight_smile:


So if you indent a while loop like this

while condition:
    if this condition is met:
        return this value:
        return this value

With this indentation level. Nothing points to your while loop, thus resulting in the editor asking if you even included an else statement in your while loop. always remember For your loops to work well. Your else if there is one, or return statements should be indented to the same level as your loop.


So, I guess my next question is, even with the proper indentation, why is my program not stopping after three guesses like it should?


Because you decrement your loop at the wrong place. This line ,

guesses_left -= 1

Should be right after the break statement and should have the same indentation as your if statement.


Jeez. Duh. That makes too much sense, as it's the logical order to follow. Thanks!


you're welcome :slight_smile: