Python Leave Loop Early

后端 未结 4 2217
执念已碎
执念已碎 2020-12-11 00:10

How do I leave a loop early in python?

for a in b:
    if criteria in list1:
        print \"oh no\"
        #Force loop i.e. force next iteration without go         


        
相关标签:
4条回答
  • 2020-12-11 00:20

    Firstly, bear in mind it might be possible to do what you want with a list comprehension. So you might be able to use something like:

    somelist = [a for a in b if not a.criteria in otherlist]
    

    If you want to leave a loop early in Python you can use break, just like in Java.

    >>> for x in xrange(1,6):
    ...     print x
    ...     if x == 2:
    ...         break
    ...
    1
    2
    

    If you want to start the next iteration of the loop early you use continue, again just as you would in Java.

    >>> for x in xrange(1,6):
    ...     if x == 2:
    ...         continue
    ...     print x
    ...
    1
    3
    4
    5
    

    Here's the documentation for break and continue. This also covers else clauses for loops, which aren't run when you break.

    0 讨论(0)
  • 2020-12-11 00:21

    Take a look at break and continue.

    0 讨论(0)
  • 2020-12-11 00:22

    continue and break work exactly like in other programming languages, except that you cannot break to a label (as you can in Java, for example). That means you can only break one loop at a time.

    0 讨论(0)
  • 2020-12-11 00:36

    continue and break is what you want. Python works identically to Java/C++ in this regard.

    0 讨论(0)
提交回复
热议问题