Login
📚 Introduction to Python Programming
Chapters ▾
⇩ 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.