8/19 Don't Understand Else Indentation


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>
https://www.codecademy.com/courses/learn-python/lessons/loops/exercises/your-own-while--else?action=lesson_resume

<In what way does your code behave incorrectly? Include ALL error messages.>
From previous exercises, I thought that when doing an “if” loop, the “if,” “elif” and “else” commands were supposed to be inline with each other, like so:

number = 6
if number == 5:
print "hello"
elif number == 3:
print "goodbye"
else:
print “howdy”

But in this activity, the correct code has the “else” command lined up with the “while” command, and NOT lined up with the “if” command (see below).
<What do you expect to happen instead?>
I’m not sure; I just do not understand when things are considered to be “inside” of loops, when it matters, and indentation in general. I don’t feel like this ha been explained and I’m getting frequent error messages and unexpected behavior due to indentation problems, which is frustrating. Can someone help me out or refer me to a concept I may have missed?

```python

This is the correct code from the exercise:

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
print “Guesses left: %s” %(guesses_left)
else:
print “You lose.”

<do not remove the three backticks above>

#2

The else in your code is bound to the the while so should have the same indentation as the opening line of that loop.

If that line is not expected, then try to pass the exercise without that line included. You can always add it later.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.