breaking out of nested loop

Discussion in 'Python' started by rbt, Jul 12, 2005.

  1. rbt

    rbt Guest

    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
    rbt, Jul 12, 2005
    #1
    1. Advertising

  2. rbt

    Fuzzyman Guest

    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
    Fuzzyman, Jul 12, 2005
    #2
    1. Advertising

  3. rbt

    Peter Hansen Guest

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


    Define a flag first:

    keepGoing = True

    > while 1:

    while keepGoing:

    > for x in xrange(len(group)):
    > try:

    ....
    > if match == target:
    > print "Collision!!!"
    > print make_string


    Set the flag here, then do the break:
    keepGoing = False

    > break


    Tada...

    -Peter
    Peter Hansen, Jul 12, 2005
    #3
  4. rbt

    rbt Guest

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

    On Tue, 2005-07-12 at 10:51 -0400, Peter Hansen wrote:
    > rbt wrote:
    > > What is the appropriate way to break out of this while loop if the for
    > > loop finds a match?

    >
    > Define a flag first:
    >
    > keepGoing = True
    >
    > > while 1:

    > while keepGoing:
    >
    > > for x in xrange(len(group)):
    > > try:

    > ...
    > > if match == target:
    > > print "Collision!!!"
    > > print make_string

    >
    > Set the flag here, then do the break:
    > keepGoing = False
    >
    > > break

    >
    > Tada...
    >
    > -Peter
    rbt, Jul 12, 2005
    #4
  5. rbt

    Duncan Booth Guest

    rbt wrote:

    > 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 ...
    Duncan Booth, Jul 12, 2005
    #5
  6. On Tue, 12 Jul 2005 10:19:04 -0400, rbt wrote:

    > 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



    --
    Steven.
    Steven D'Aprano, Jul 12, 2005
    #6
  7. rbt wrote:

    > 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...

    --
    Jeremy Sanders
    http://www.jeremysanders.net/
    Jeremy Sanders, Jul 12, 2005
    #7
  8. "rbt" <> wrote in message
    news:...

    > 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.
    Andrew Koenig, Jul 12, 2005
    #8
  9. On Tue, 12 Jul 2005 10:19:04 -0400, rbt <>
    declaimed the following in comp.lang.python:

    > 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

    --
    > ============================================================== <
    > | Wulfraed Dennis Lee Bieber KD6MOG <
    > | Bestiaria Support Staff <
    > ============================================================== <
    > Home Page: <http://www.dm.net/~wulfraed/> <
    > Overflow Page: <http://wlfraed.home.netcom.com/> <
    Dennis Lee Bieber, Jul 12, 2005
    #9
  10. [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
    Raymond Hettinger, Jul 13, 2005
    #10
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Amy
    Replies:
    0
    Views:
    504
  2. Tim Golden

    RE: breaking out of nested loop

    Tim Golden, Jul 12, 2005, in forum: Python
    Replies:
    1
    Views:
    367
    Dennis Lee Bieber
    Jul 13, 2005
  3. Tagore

    breaking out of multiple nested loops

    Tagore, Nov 15, 2009, in forum: C Programming
    Replies:
    42
    Views:
    2,015
    Gus Gassmann
    Dec 5, 2009
  4. Hemant Shah

    Breaking out of nested subroutine?

    Hemant Shah, Jul 29, 2004, in forum: Perl Misc
    Replies:
    30
    Views:
    714
    David Combs
    Aug 7, 2004
  5. Isaac Won
    Replies:
    9
    Views:
    372
    Ulrich Eckhardt
    Mar 4, 2013
Loading...

Share This Page