[Tutor] 'for' iteration stop problem

Alan Gauld alan.gauld at btinternet.com
Sun Apr 3 00:45:49 CEST 2011


"Mateusz Korycinski" <mat.korycinski at gmail.com> wrote

> My problem is simple for sure, but unfortunately I'm a bit beginner 
> and I've
> stucked in it. I hope it is not a problem since as I understand this 
> mailing
> list is for beginners.

No problem, we try to answer questions such as this here.

> I have some problem with 'for' loop in algorithm.
> Code and description for this problem could be find here:
> http://stackoverflow.com/questions/5520145/how-to-stop-iteration-when-if-statement-is-true

There are several ways to get out of a loop, the most common are:

a) To exit a single level of loop use break


for n in range(500):
    if n == 200: break
    else; pass

b) To break out of a set of nested loops such as you have then
use break combined with a sentinal and check the sentinal at
each level:

exitLoop = False
for x in range(20):
    if exitLoop : break
    for y in range(50):
        if exitLoop: break
        for z in range(500):
            if z == 200:
              exitLoop = True
              break

c) Use an exception:

class ExitLoopException(Exception): pass

try:
  for x in range(20):
    for y in range(50):
        for z in range(500):
            if z == 200:
               raise ExitLoopException
except ExitLoopException: pass


There are other ways but those should cover most eventualities.

HTH,

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




More information about the Tutor mailing list