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 break
and continue
inside loops, I was wondering whether Python allowed to write for
loops without them. I would say that Python doesn't allow this (and maybe it would go against the "one way to do it" rule).
EDIT2: Commenters have made me notice that return
could be used instead, but that would not be a solution, either.
You can also use
sys.exit()
The
break
andcontinue
keywords only have meaning inside a loop, elsewhere they are an error.Anyone who says
break
andcontinue
should not be used is not teaching good Python.You could always use a function and return from it:
Although using
break
is more elegant in my opinion because it makes your intent clearer.You could use a boolean value to check if you are done. It will still iterate the rest of the loop but not execute the code. When it is done it will continue on its way without a break. Example Pseudo code below.