Naming Loops in Python

前端 未结 4 2009
旧巷少年郎
旧巷少年郎 2020-12-03 17:32

I recently read this question which had a solution about labeling loops in Java.

I am wondering if such a loop-naming system exists in Python. I have been in a situa

4条回答
  •  庸人自扰
    2020-12-03 17:47

    Though there are reasons to include named looped in language construct you can easily avoid it in python without loss of readability. An implementation of the referred example in python

    >>> try:
        for i in xrange(0,5):
            for j in xrange(0,6):
                if i*j > 6:
                    print "Breaking"
                    raise StopIteration
                print i," ",j
    except StopIteration:
        print "Done"
    
    
    0   0
    0   1
    0   2
    0   3
    0   4
    0   5
    1   0
    1   1
    1   2
    1   3
    1   4
    1   5
    2   0
    2   1
    2   2
    2   3
    Breaking
    Done
    >>> 
    

    I solve this problem by putting the inner loop in a function that returns (among others) a boolean which is used as a breaking condition.

    I think you should try this. This is very pythonic, simple and readable.

提交回复
热议问题