The else clause of a loop (either a for or a while statement) executes immediately after the loop terminates normally. If there is a break statement in the loop body, then the else clause is skipped. If there is no break statement, then the else clause will always be executed after the loop, unless it exits with a return or raise. Therefore, if there is no break statement in the loop body then the else clause can be replaced with unindented code.

Generally the use of else clauses should be avoided where possible, as they are likely to be misunderstood.

Replace the else clause with unindented code.

In this example, the pointless_else function contains a redundant else clause. The else clause can be simplified, as shown in the no_else function, which has the same semantics, but has no else clause. The third example function, with_break, shows a version where the else clause is necessary, as the break statement skips the else clause.

  • Python Language Reference: The while statement.
  • Python Tutorial: Break and continue statements, and else clauses on loops.