[Tutor] For/else construct was: Re: (no subject)
Alan Gauld
alan.gauld at btinternet.com
Wed Feb 8 23:25:58 CET 2012
On 08/02/12 19:04, Patrick Dempster wrote:
> I might be missing something but I can't see a reason for the "else:"
> clause attached to the "for" statement, could anyone provide an example
> where or why someone might use the "else:" clause with the for loop?
There have been a couple of sample cases given already but here is an
example of what you would need to do without it.
broken_loop = False
for item in collection:
process(item)
if condition:
broken_loop = True
break
if not broken_loop:
do_the_else_part()
do_this_regardless()
It's not a huge pain but this is easier:
for item in collection:
process(item)
if condition:
break
else:
do_the_else_part()
do_this_regardless()
HTH,
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list