[Tutor] For - if - else loop; print selective output

Sander Sweers sander.sweers at gmail.com
Thu Oct 25 02:45:18 CEST 2012

Alan Gauld schreef op wo 24-10-2012 om 17:49 [+0100]:
> I confess I'm not keen on the else part of a for loop and never use
> it, 
> I think it leads to more confusion than anything. It doesn't do what 
> most folks seem to expect, it should probably be called 'end' or 
> something similar rather than 'else' IMHO.
>  >>> for n in range(5):
> ...    print n,
> ... else:
> ...    print 'done!'
> ...
> 0 1 2 3 4 done!
>  >>> for n in range(5):
> ...    if n < 3: print n,
> ...    else: break
> ... else: print 'done!'
> ...
> 0 1 2 

This confused me somewhat and after a little experimenting and looking
at the docs [1] I now get what you hint at (but do not spell out :-)).
The devil is in the break statement. I _try_ to describe this below
based on the docs and the experimentation in the hope that other people
find it useful.

Loops (for and while) can have an optional else clause. The else clause
is always executed *unless* you call the break statement in your loop.
If you call a break statement in your loop the else clause is never
executed. If the break statement is never called the else clause is

break statements in *nested* loops do *not* interfere with the else
clause the parent loop and vice versa. It only applies to the current
loop the break statement is called in.

There is a good example for prime numbers in the docs.

More information about the Tutor mailing list