Skipping Iterations with Continue Statements
In this lesson, you will learn how to use the continue statement to skip the remainder of a loop's current cycle and jump straight to the next iteration.
The Power of Skipping
Sometimes, while looping through a list or a range of numbers, you encounter a situation where you want to ignore a specific item and move on to the next one immediately. Instead of wrapping your entire loop logic inside a giant if/else block, you can use continue to "short-circuit" the rest of the code inside the loop for that particular iteration.
When Python hits the continue keyword, it stops executing any code below it for the current loop cycle, goes back to the top, and starts the next iteration as if nothing happened.
Practical Example
Imagine you are printing numbers from 1 to 5, but you want to skip the number 3 specifically:
for number in range(1, 6):
if number == 3:
continue
print(f"Processing number: {number}")
print("Loop finished!")
What happens here?
- The loop starts and prints 1 and 2 normally.
- When
numberbecomes 3, theifcondition isTrue, andcontinuetriggers. - Python skips the
printstatement for 3 and immediately jumps to the next cycle wherenumberis 4. - It finishes by printing 4 and 5.
Notice how the print function was bypassed only for the number 3. This keeps your code clean and avoids deep, nested indentation when you have "special cases" to handle within a list of items. It is a powerful tool to streamline your logic whenever you need to filter out noise while processing data.
Key Takeaway: The continue statement acts like a "skip" button, immediately ending the current iteration of a loop so the program can move to the very next item in the sequence.