Loop Control (break & continue)
Control loop execution with break and continue. Read the lesson first, then move through the exercises in order.
After reading
Practice Arena
Begin with the first exercise, then continue step by step through the module.
Start with First Negative NumberStudy Material
Read the full lesson
Taking the wheel
Usually, a loop runs until it reaches the end of its collection or its condition becomes false.
But sometimes, you need to intervene. Maybe you found the exact item you were searching for, or maybe you encountered data you want to skip.
Python provides two powerful keywords to control the flow of loops: break and continue.
The break keyword
break acts like an emergency exit. The moment Python hits a break statement, the loop instantly stops, and the program moves on to the code after the loop.
pythonfor number in range(1, 100): print(f"Searching... currently at {number}") if number == 5: print("Found the target! Stopping the search.") break # <--- Emergency exit! print("Loop has finished.")
Even though the loop was scheduled to run 99 times, it stops completely the moment condition == 5 is met because of the break statement.
The continue keyword
continue is like a "skip" button. Instead of destroying the entire loop like break, continue just skips the rest of the current iteration and immediately jumps back to the top of the loop for the next item.
pythonfor i in range(1, 6): if i == 3: print("Skipping number 3...") continue # <--- Jump back to the top! print(f"Processing number {i}")
Output:
Processing number 1 Processing number 2 Skipping number 3... Processing number 4 Processing number 5
Notice how "Processing number 3" never prints. The continue statement forced Python to ignore the rest of the code block for that specific cycle.
Infinite loops and break
A very common pattern in Python is to intentionally write an infinite loop using while True:, and then use a break statement when the user inputs a specific command to quit.
pythonwhile True: command = input("Type 'q' to quit: ") if command == 'q': print("Goodbye!") break print("Keep going...")
What this lesson should give you
After this lesson, you should understand how to:
- use
breakto completely escape and terminate a loop early - use
continueto skip the rest of the current iteration and move to the next one - combine
while True:andbreakto create controllable interactive loops
Interactive
Exercises for this topic
These exercises follow the exact order of the lesson. Move step-by-step from reading into coding.
First Negative Number
Complete the "First Negative Number" exercise.
Print Only Odd Numbers
Complete the "Print Only Odd Numbers" exercise.
Prime Number Check
Complete the "Prime Number Check" exercise.
Search and Exit Early
Complete the "Search and Exit Early" exercise.
Skip Vowels
Complete the "Skip Vowels" exercise.