For else loop


#1

Can anyone please tell me the actual use of for/else loop? As i saw that the else loop will only work if the for loop ends normally. Anyway if we add any code after for loop that will be executed. So what is the purpose of adding a else?


#2

The general premise is that our loop will end routinely or it will be interrupted. The else plays a crucial role because it reads and interprets that interruption.


#3

if you want to make a number guess game you could do:

while guesses_left:
   if correct_guess:
       print "you win"
       break

else:
    print "you lose"

you don’t want to inform the user they lost after they won, which is why else is crucial


#4

Notwithstanding the else that would be present to increment guesses_left.


#5

do you have to? You could simply do:

while guesses_left:
   if correct_guess:
       print "you win"
       break
    guesses_left -= 1

else:
    print "you lose"

else isn’t strictly necessary.

but i admit, i forgot about that bit, was focused on for/else

i decrease guesses_left, but increment is of course also possible.


#6

Given the break is like a return it follows the next line is not conditional. Very good!


#7

exactly. Well, piece of cake. Its one of the exercises here on codecademy, seen it so many times by now :wink:


#8

But you know how short my memory is…


#9

Without intuition I’d have no memory at all.


#10

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