Noob: Loops and the 'else' construct

Ixiaus parnell.s at comcast.net
Thu Oct 18 22:44:25 EDT 2007


I have just come across a site that discusses Python's 'for' and
'while' loops as having an (optional) 'else' structure.

At first glance I interpreted it as being a bit like the 'default'
structure in PHP's switch block... But the switch block isn't a loop,
so, I am now confused as to the reason for using 'else' with the for
and while loops...

A few quick tests basically show that statements in the else structure
are executed at the fulfillment of the loop's expression (ie, no
break).

Example:

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

0
1
2
3
4
5
6
7
8
9
10
the end!




More information about the Python-list mailing list