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?
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.
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
else that would be present to increment
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
i decrease guesses_left, but increment is of course also possible.
break is like a
return it follows the next line is not conditional. Very good!
exactly. Well, piece of cake. Its one of the exercises here on codecademy, seen it so many times by now
But you know how short my memory is…
Without intuition I’d have no memory at all.
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.