else clauses in while and for loops
Donn Cave
donn at oz.net
Tue Apr 18 02:55:24 EDT 2000
Quoth "Jeff Massung" <jmassung at magpiesystems.com>:
| Donn Cave wrote in message <8dg14u$f08$1 at nntp6.u.washington.edu>...
|> 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.
|
| I don't think that I'm following you, give me an example where the loop
| ends, but the else wouldn't be executed and I think I'll better understand.
OK, let's bring back the example from a few posts back:
for envname in ['TMPDIR', 'TMP', 'TEMP']:
if os.environ.has_key(envname):
path = [os.environ[envname]]
basepaths = validate_paths(path)
if basepaths:
break
else:
basepaths = validate_paths(_tmpdirs)
Here the else branch executes if none of the envnames turns up
in environ. The conditions to break out are 1) envname is there,
and 2) validate_paths() can use it; if those conditions are never
met, the else clause executes.
Now it's simpler to say "else executes if break doesn't". I'm
just trying to complicate matters with a formula that tries to
make sense in terms of the common usage of "else" in other familiar
contexts.
Donn Cave, donn at oz.net
More information about the Python-list
mailing list