breaking out of nested loop

Raymond Hettinger python at rcn.com
Wed Jul 13 09:57:19 EDT 2005


[rbt]
> What is the appropriate way to break out of this while loop if the for
> loop finds a match?
>
> while 1:
>     for x in xrange(len(group)):
>         try:
>             mix = random.sample(group, x)
>             make_string = ''.join(mix)
>             n = md5.new(make_string)
>             match = n.hexdigest()
>             if match == target:
>                 print "Collision!!!"
>                 print make_string
> 		Stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime())
> 		print "Stop", Stop
>                 break
>             else:
>                 continue
>         except Exception, e:
>             print e

I would wrap the whole thing in a function definition.  When you find a
match, just return from the function.  Besides cleanly exiting from
multiple loops, the function approach usually leads to better factoring
(in this case, segregating the search logic from everything else).


Raymond




More information about the Python-list mailing list