Stopping an iteration without using `break` in Python 3

后端 未结 4 1433
春和景丽
春和景丽 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:46

    The break and continue keywords only have meaning inside a loop, elsewhere they are an 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's moves
            ...
    

    Anyone who says break and continue should not be used is not teaching good Python.

提交回复
热议问题