Stopping an iteration without using `break` in Python 3

后端 未结 4 1412
春和景丽
春和景丽 2021-01-20 12:02

For example, can this code be rewritten without break (and without continue or return)?

import logging

for i, x in en         


        
4条回答
  •  抹茶落季
    2021-01-20 12:39

    You could 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 using break is more elegant in my opinion because it makes your intent clearer.

提交回复
热议问题