for: else: - any practical uses for the else clause?
BJörn Lindqvist
bjourne at gmail.com
Sat Sep 30 15:05:46 EDT 2006
> How do you transform this?
>
> height = 0
> for block in stack:
> if block.is_marked():
> print "Lowest marked block is at height", height
> break
> height += block.height
> else:
> raise SomeError("No marked block")
def get_height_of_first_marked_bock(stack):
height = 0
for block in stack:
if block.is_marked():
return height
height += block.height
raise SomeError("No marked block")
height = get_height_of_first_marked_block(stack)
print "Lowest marked block is at height", height
Yes, this transformation is one line longer, but the control flow is
much easier to understand. In general, using the for/else clause mixes
the retrieval and the usage of the element. Consider this:
for item in list:
if somecond(item):
A) do something with item
break
else:
B) exceptional code when somecond() doesnt match anything in list
The code that you write in the positions A and B really are misplaced.
They arent part of the iteration of list. The two tasks, find item and
do something with item should be separated.
def find_item(list):
for item in list:
if somecond(item):
return item
return None # OR raise an exception
item = find_item(list)
if item:
A) do something with item
else:
B) exceptional code
This is, IMHO, much better style.
--
mvh Björn
More information about the Python-list
mailing list