History question about for .. else
David Bolen
db3l at fitlinxx.com
Tue Nov 7 21:36:38 EST 2000
Dave Cole <djc at object-craft.com.au> writes:
> I just used the else clause on a for loop for the first time and my
> business partner does not like it. We launched into a discussion
> about the construct.
>
> for value in list:
> if condition:
> # do something
> break
> else:
> # do something else
>
> My partner is of the opinion that the syntax is ugly, and he would
> avoid it if at all possible. I argued that it is a zero-cost
> detection of "falling of the end of the loop" as it prevents you
> having to use an additional condition variable and subsequent test.
>
> I would be interested in knowing the history behind the introduction
> of the else clause on the for loop.
It sort of seems difficult to understand why:
found = 0
for value in list: for value in list:
if condition: if condition:
# do something could be # do something
found = 1 less ugly break
break than ->
if not found: else:
# do something # do something
I can't speak directly to the history, but I know that my own code in
the past has often used the flag pattern (although in C code I in a
for loop I sometimes avoid the flag variable in favor of just
inverting the for termination expression), so I was actually
pleasantly surprised to see it so directly supported (and to me
elegantly) by Python.
--
-- David
--
/-----------------------------------------------------------------------\
\ David Bolen \ E-mail: db3l at fitlinxx.com /
| FitLinxx, Inc. \ Phone: (203) 708-5192 |
/ 860 Canal Street, Stamford, CT 06902 \ Fax: (203) 316-5150 \
\-----------------------------------------------------------------------/
More information about the Python-list
mailing list