Introduction to Python ProgrammingXYZ Homework Edition

⇩ Download ▾

5.5 Loop else

Learning objectives

By the end of this section you should be able to

  • Use loop else statement to identify when the loop execution is interrupted using a break statement.
  • Implement a loop else statement with a for or a while loop.

Loop else

A loop else statement runs after the loop's execution is completed without being interrupted by a break statement. A loop else is used to identify if the loop is terminated normally or the execution is interrupted by a break statement.

Ex: A for loop that iterates over a list of numbers to find if the value 10 is in the list. In each iteration, if 10 is observed, the statement "Found 10!" is printed and the execution can terminate using a break statement. If 10 is not in the list, the loop terminates when all integers in the list are evaluated, and hence the else statement will run and print "10 is not in the list." Alternatively, a Boolean variable can be used to track whether number 10 is found after loop's execution terminates.

Adapted from Introduction to Python Programming by OpenStax (openstax.org), licensed under CC BY-NC-SA 4.0. Changes were made. License: CC-BY-NC-SA-4.0.

These eBooks are a prerelease and are not yet certified conformant with WCAG 2.1 AA or ADA Title II. Every page is built against an automated accessibility gate, and the published editions will meet ADA Title II requirements when they release in late September 2026. If something is unusable, please tell us.