Stopping An 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)
Solution 1:
You could always use a function and return from it:
import logging
deffunc():
for i, x inenumerate(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 using break
is more elegant in my opinion because it makes your intent clearer.
Solution 2:
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.
doneLogging = Falsefor i, x inenumerate(x):
ifnot 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
Solution 3:
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)
Solution 4:
The break
and continue
keywords only have meaning inside a loop, elsewhere they are an error.
for grooble in spastic():
ifhasattr(grooble, '_done_'):
# no need for futher processing of this elementcontinueelif grooble is TheWinner:
# we have a winner! we're done!breakelse:
# process this grooble's moves
...
Anyone who says break
and continue
should not be used is not teaching good Python.
Post a Comment for "Stopping An Iteration Without Using `break` In Python 3"