In this lesson, you will learn how to take manual control of your loops by jumping out of them or skipping ahead to the next item.
So far, you’ve used while and for loops to repeat code until a sequence ends or a condition is met. Sometimes, however, you need to change that flow based on a specific event. Python gives us two keywords for this: break and continue.
The break Statement
The break keyword stops the loop immediately. Think of it like an "emergency exit." Once Python hits a break statement, the loop ends completely, and the program moves on to the code immediately following the loop.
Imagine you are searching for a specific item in a list:
numbers = [1, 2, 99, 4, 5]
for num in numbers:
if num == 99:
print("Found it! Stopping the search.")
break
print(f"Checking number: {num}")
In this example, as soon as the code sees 99, it executes break. The numbers 4 and 5 are never checked because the loop is terminated.
The continue Statement
The continue keyword is less "final" than break. Instead of stopping the whole loop, it tells Python to stop the current iteration and jump immediately back to the top to start the next one. Use this when you want to skip over specific items but keep the loop running.
for num in range(1, 6):
if num == 3:
continue
print(f"Processing number: {num}")
Here, when num is 3, the continue statement triggers. The print function is skipped for that number, but the loop continues on to process 4 and 5.
When to use which?
- Use
breakwhen you have found what you are looking for or a condition makes continuing the loop useless. - Use
continuewhen you want to ignore specific data points while still processing the rest of your sequence.
Key Takeaway: Use break to exit a loop entirely, and use continue to skip the remainder of the current iteration and jump to the next one.