Forainxrange (10): forbinxrange (20): ifsomething (a, B): # Breaktheinnerloop... breakelse: # Continueiftheinnerloopwasntbroken.
For a in xrange (10): for B in xrange (20): if something (a, B): # Break the inner loop... break else: # Continue if the inner loop wasn' t broken. continue # Inner loop was broken, break the outer. break
Reply: I can't help but say something ...... You never read official documents when learning python. Did you just follow the Chinese tutorial of XX?
The Python loop body has its own else branch!
The Python loop body has its own else branch!
The Python loop body has its own else branch!
Not only if, but both while and for have else branches.
The trigger condition for the else branch of the loop body is that the loop ends normally.. If a break exists in the loop, else is not executed. Therefore, the logic is: if the break in the loop does not trigger else, the break in the next outer loop is executed; if it ends normally, the continue in the else branch is executed, jump directly to the next round of the outer loop and skip the second break.
But Nima is ugly ...... Is it possible to make a Boolean ......
--------
In fact, the correct posture should be to wrap up a function and then use return ...... After an exception is thrown, The else clause for and while is used for loop post-processing. The clause is executed only when the loop ends normally.
In the example above, setting a flag variable makes the code more intuitive.
It's hard to say which method is better. I like else branch very much.