1.5.2 for: else:
John Max Skaller
skaller at maxtal.com.au
Wed Aug 4 02:24:59 EDT 1999
On Thu, 29 Jul 1999 08:51:15 +1200, Greg Ewing <greg.ewing at compaq.com> wrote:
>Gordon McMillan wrote:
>>
>> But finding a match in a list, and testing whether you
>> fell off the end without finding one, is (without the else clause) a
>> much messier proposal.
>
>Not if you go about it the right way. I always
>put such loops in a procedure of their own,
>and use return:
>
> def find_the_holy_grail(stuff):
> for x in stuff:
> if is_holy_grail(x):
> return x
> return None
Unfortunately, python lacks lexical scoping, which means this technique
cannot be easily generalised. In particular, if the loop body requires
access to the current context, you can't use a function to encapsulate it.
John Max Skaller ph:61-2-96600850
mailto:skaller at maxtal.com.au 10/1 Toxteth Rd
http://www.maxtal.com.au/~skaller Glebe 2037 NSW AUSTRALIA
More information about the Python-list
mailing list