Programming fundamentalsLesson 5 of 5 in the course Loops

Python Loop else: Normal Completion and break

5 flashcards · 4 quiz questions · 5 match pairs · 4 fill-in sentences · English

Lesson progress
0 / 5

Your progress is kept in this browser only.Sign up to save it

Summary

A loop can finish in two different ways: it can complete all its iterations normally, or it can be interrupted by a break statement. Python’s loop else clause helps distinguish these outcomes.

The else clause belongs to the loop, not to an if statement inside it. It runs when the loop finishes normally—that is, when a for loop has no more items to process or a while loop’s condition becomes false. If the loop exits because it executes break, the loop’s else clause is skipped.

All flashcards

Python loop else clause
A block that runs after a for or while loop finishes normally without break.
Effect of break on loop else
Executing break exits the loop and skips its else clause.
Loop else in a search
Break when the target is found; otherwise, else can report that no match was found.
Indentation of loop else
The else keyword aligns with the for or while keyword.
Printing a sum after a loop
Put the print statement in else to print the total only if the loop finishes without break.

Quiz questions

  1. In Python, a while loop with an else clause reaches a false condition without executing break. What happens?Answer: The loop's else block runs.
  2. A Python for loop has an else clause and iterates over an empty list. No break is executed. Does the else clause run?Answer: Yes, the loop completes normally.
  3. A Python loop searches [2, 5, 7, 11, 12] for 10, prints "Found 10!" and breaks if it finds the target; its else prints "10 is not in the list." What is printed?Answer: 10 is not in the list.
  4. A Python loop adds each value in [2, 5, 7] to a total, breaks for values greater than or equal to 10, and prints the total in else. What is printed?Answer: 14

Based on Introduction to Python Programming by Udayan Das, Aubrey Lawson, Chris Mayfield, Narges Norouzi (OpenStax), licensed CC BY 4.0. Adapted into a summary, flashcards and quizzes.

All Programming fundamentals lessons