[Tutor] While and for loops

Alan Gauld alan.gauld at btinternet.com
Tue Jul 14 09:44:51 CEST 2009


"wesley chun" <wescpy at gmail.com> wrote 

> as i mentioned in my other msg, you need another break statement that
> is *not* in another loop. in your case, not in the for-loop. you need
> a break statement somewhere within your while block (again, that's not
> in any other loop). IOW, it should be indented at the same level as
> the for-loop. it's up to you to determine the logic with which you
> call your break, because if you just put it out there, your while will
> only run at most once (or less than once).

And for completeness that would probably look like:

while True:
    <do something>
    for i in items:
        if i > 10:
            break    # out of the for
        else:
            <do something>
    if i > 10:
        break   # out of the while under the same conditions

But as Wesley said, for this specific case the Found / notFound 
sentinel approach is nicer.

Although there is a school of thought says break statements 
are only slightly less evil than goto and should be avoided if 
possible. In that case you can do it by inverting the logic of 
the tests:

i = 0
while i <= 10:
    <do something>
    for i in items:
        if i <= 10:
           <do something>

But, as usual with purist approaches the result might look 
neater buts it is far less efficient and less flexible!

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list