else clauses in while and for loops

Donn Cave donn at u.washington.edu
Mon Apr 17 17:53:34 EDT 2000


Quoth "Jeff Massung" <jmassung at magpiesystems.com>:
| I'm new to Python, so perhaps I'm miss reading something in these posts, but
| it appears as though the "else" statement (especially in while loops -
| unless infinite) always get executed regardless.
|
| i = 0
| while i<=5:
|     i = i + 1
|     print i
| else:
|     print 10
|
| should spit out "1 2 3 4 5 10" right?

Yes, but if you look at the examples, they also use "break".  After a
loop, "else" basically means "if no iteration of the loop met the
conditions to break out."  It's a common usage, where in C we'd compare
the final loop index with the maximum (or whatever) loop index to see
if the loop ran all the way through.

| Now a use that I could definitely see for the "else" would be if the loop
| were never entered at all! Example:
|
| i = 6
| while i<=5:
|     i = i+1
|     print i
| else:
|     print 10
|
| would print "10", and if 'i' started at 0, would print "1 2 3 4 5".
|
| That could definitely be useful, because it would eliminate an "if"
| statement right before the "while" statement. Extremely useful for debugging
| purposes.

I think I would go along with that if you took out "Extremely" - and then
your paragraph would justify better on the right margin, too!  Seriously,
"else" does invariably execute if the loop was never run once, but as
mentioned above it also executes in other circumstances.

	Donn Cave, University Computing Services, University of Washington
	donn at u.washington.edu



More information about the Python-list mailing list