Why the else is not indented


#1


why the answer provided in this lessen the else is not indented with the same level with if?
Hi people,
why the answer provided in this lessen the else is not indented with the same level with if?

Can I write the code as:
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.”

Thank you


#2

Because the else actually applies to the while! :smiley: The else clause is like a finally clause in this respect, where it is ultimately executed when the while clause exits.

In the following syntax, the while loop would continue until exhausted and then the else clause would kick in to top it off:

a = 0
while a < 3:
    print(a)
    a += 1
else:
    print('Done!')

Can you guess what this will output?

0
1
2
Done!

#3

while :
else:

would have the same indentation. The purpose of else in this case is for when there is a break conditional in the loop.

from random import randint
count = 0
while count < 5:
    a = randint(1, 10)
    print(a)
    if a == 5: break
    count += 1
else:
    print('Done!')
print('Bye')
4
9
5
Bye
6
10
1
8
2
Done!
Bye


#4

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