Suppose you have the following code:
for in range: if i = = 5 :print'found it! i =%s ' % ielse: print'notfound it ... '
The result you expect is that when found 5 o'clock print out:
Found it! i = 5
The results are actually printed as:
Found it! i = 5 not found it ...
Obviously this is not the result we expect.
According to the official documentation:
>when the items are exhausted (which isImmediately when the sequence isEmpty), the suiteinchTheElseClauseifPresent isExecuted andThe loop terminates.>a BreakStatement executedinchThe first suite terminates the loop without executing theElseClause ' s suite. AContinueStatement executedinchThe first suite skips the rest of the suite andContinues with the next item,orWith theElseClauseifthere was no next Item.https:Docs.python.org/2/reference/compound_stmts.html#the-for-statement
The main idea is that when an iteration of an object is iterated and empty, the clause at else is executed, and if a break is included in the For loop, the loop is terminated, and the ELSE clause is not executed.
So the correct wording should be:
for in range: if i = = 5: print'found it! i =%s ' % i breakElse: print' not found it ... '
When you use Pylint to detect code, you are prompted
break statement (useless-else-on-loop)
So it is necessary to develop the habit of using Pylint to detect code, and it is difficult to notice such logic errors.
MMM ~
Reprinted from: https://www.cnblogs.com/dspace/p/6622799.html
Python for loop paired with else traps