Programming fundamentalsLesson 3 of 3 in the course Loops

Python Loop Control with break and continue

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

Lesson progress
0 / 5

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

Summary

Loops repeat a block of code, but sometimes a program needs to stop a loop early or skip part of one iteration. Python’s break and continue statements provide these controls.

The break statement immediately exits the nearest enclosing for or while loop. Execution continues with the first statement after that loop. It is useful when a task is complete and further iterations are unnecessary, such as when a search finds the item it needs.

All flashcards

What does break do inside a loop?
It immediately exits the nearest enclosing for or while loop. Execution resumes after that loop.
What does continue do inside a loop?
It skips the rest of the current iteration and proceeds to the next iteration.
When is break useful in a search?
When the target has been found and checking more items is unnecessary.
How can break stop a while True loop?
Use a reachable condition inside the loop that executes break when the loop should stop.
What should you check when using continue in a while loop?
Make sure necessary updates still occur so the loop can reach its stopping condition.

Quiz questions

  1. What does a break statement do when it executes inside nested loops?Answer: It exits the nearest enclosing loop, then execution continues after that loop.
  2. What happens after continue executes inside a loop?Answer: The rest of the current iteration is skipped, and the loop proceeds to its next iteration.
  3. A Python loop scans a string character by character and should stop after finding a space. Which statement should it use after recording the match?Answer: Use break to exit the loop after the space is found.
  4. What does this code print? ```python counter = 1 while True: if counter >= 10: break print(counter) counter += 1 ```Answer: The integers from 1 through 9.
  5. What does this code print? ```python for number in range(6): if number % 2 == 0: continue print(number) ```Answer: The integers 1, 3, and 5.

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