breaking out of nested loop

R

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
 
F

Fuzzyman

You either need to set a marker flag with multiple breaks - *or*
(probably more pythonic) wrap it in a try..except and raise an
exception. Define your own exception class and just trap for that if
you want to avoid catching other exceptions.

There is no single command to break out of multiple loops.

Regards,

Fuzzy
http://www.voidspace.org.uk/python
 
R

rbt

Thanks guys... that works great. Now I understand why sometimes logic
such as 'while not true' is used ;)
 
D

Duncan Booth

rbt said:
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)):

another option not yet suggested is simply to collapse the two loops into a
single loop:

import itertools

for x in itertools.cycle(range(len(group)):
... as before ...
 
S

Steven D'Aprano

What is the appropriate way to break out of this while loop if the for
loop finds a match?

Refactor it into something easier to comprehend?

And comments never go astray.


(Untested. And my docstrings are obviously bogus.)

def make_one_thing(group, x):
"""Makes a thing by plonking the frobber.
Expects group to be a list of foo and x to be an index.
"""
mix = random.sample(group, x)
make_string = ''.join(mix)
n = md5.new(make_string)
match = n.hexdigest()
return match

def group_matches(group, target):
"""Cycles over a group of foos, plonking the frobber of each
item in turn, and stopping when one equals target.
"""
for x in xrange(len(group)):
try:
match = make_one_thing(group, x)
if match == target:
return True
except Exception, e:
# don't stop just because the program has a bug
print e
# if we get here, there was no successful match after the
# entire for loop
return False

def test_until_success:
"""Loop forever, or until success, whichever comes first.
"""
group = [1, 2, 3, 4]
target = 5
flag = False
while not flag:
print "No matches yet, starting to search..."
flag = group_matches(group, target)
# if we ever get here, it means we found a collision, and
# flag became True, so the while loop just dropped out
print "Collision!!!"
stop = time.strftime("%H:%M:%S-%m-%d-%y", time.localtime())
print "Stopped at", stop
 
J

Jeremy Sanders

rbt said:
What is the appropriate way to break out of this while loop if the for
loop finds a match?

queue discussion why Python doesn't have a "break N" statement...
 
A

Andrew Koenig

What is the appropriate way to break out of this while loop if the for
loop finds a match?

Make it a function and use a "return" statement to break out.
 
D

Dennis Lee Bieber

What is the appropriate way to break out of this while loop if the for
loop finds a match?

Uh... test for a match ON the while? (Your indentation is also
incorrect).

NoMatch = True #<<<<<<<<<<
while NoMatch: #<<<<<<<<<<
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:
NoMatch = False #<<<<<<<<<<<
Stop = time.strftime("%H:%M:%S-%m-%d-%y",
time.localtime())
print "Collisiion"
print make_string
print Stop
break
except Exception, e:
print e

--
 
R

Raymond Hettinger

[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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,822
Latest member
israfaceZa

Latest Threads

Top