Noob: Loops and the 'else' construct

Paul Boddie paul at boddie.org.uk
Fri Oct 19 08:48:48 EDT 2007


On 19 Okt, 13:39, Dustan <DustanGro... at gmail.com> wrote:
> On Oct 19, 3:12 am, Thorsten Kampe <thors... at thorstenkampe.de> wrote:
>
> > So a for/else loop is exactly the same thing as a for loop with the
> > else clause outside the loop (except for "break")?
>
> Am I missing something here? It sounds to me like you just described
> two identical constructs.

Think of the loop-plus-else construct as behaving like this:

while 1:
    # Get next element (in a for loop)
    if loop_condition: # eg. whether we have an element
        # Loop body statement
    else:
        # Loop else statement
        break

Taking the example...

for i in range(10):
    print i
else:
    print 'the end!'

This is equivalent to...

while 1:
    # Get next element (from the range iterator)
    if next element: # yes, it's more complicated than this
        print i
    else:
        print 'the end!'
        break

Now consider what happens if you put a break statement inside the for
loop.

Paul




More information about the Python-list mailing list