Stopping iteration without using `break` in Python 3

For example, can this code be rewritten without break

(and without continue

or return

)?

import logging

for i, x in enumerate(x):
    logging.info("Processing `x` n.%s...", i)
    y = do_something(x)
    if y == A:
        logging.info("Doing something else...")
        do_something_else(x)
    elif y == B:
        logging.info("Done.")
        break

      

EDIT: Since some people criticize the use of inner loops break

and continue

, I was wondering if Python is allowed to write loops for

without them. I would argue that Python does not allow this (and it may be against the "one way to do it" rule).

EDIT2: The commenters made me notice what return

could have been used instead, but that wouldn't be a solution either.

+3


source to share


4 answers


You can always use a function and return from it:

import logging

def func():
    for i, x in enumerate(x):
        logging.info("Processing `x` n.%s...", i)
        y = do_something(x)
        if y == A:
            logging.info("Doing something else...")
            do_something_else(x)
        elif y == B:
            logging.info("Done.")
            return # Exit the function and stop the loop in the process.
func()

      



Although the use is break

more graceful in my opinion, because it makes your intent more clear.

+6


source


You can use boolean to check if you are satisfied. It will still iterate through the rest of the loop, but it will not execute the code. When this is done, he will continue on his way without interruption. Example The pseudocode is below.



doneLogging = False
for i, x in enumerate(x):
    if not doneLogging:
        logging.info("Processing `x` n.%s...", i)
        y = do_something(x)
        if y == A:
            logging.info("Doing something else...")
            do_something_else(x)
        elif y == B:
            logging.info("Done.")
            doneLogging = True

      

0


source


You can also use sys.exit()

import logging
import sys

for i, x in enumerate(x):
    logging.info("Processing `x` n.%s...", i)
    y = do_something(x)
    if y == A:
        logging.info("Doing something else...")
        do_something_else(x)
    elif y == B:
        logging.info("Done.")
        sys.exit(0)

      

0


source


Keys break

and continue

only make sense inside the loop, elsewhere they are error.

for grooble in spastic():
    if hasattr(grooble, '_done_'):
        # no need for futher processing of this element
        continue
    elif grooble is TheWinner:
        # we have a winner!  we're done!
        break
    else:
        # process this grooble moves
        ...

      

Anyone who says that break

and continue

shouldn't be used is not teaching good Python.

0


source







All Articles