Control Flow Within Loops
You can use if, break, and continue inside a loop. That lets you do different work on different iterations—for example, print only even numbers or stop as soon as you find a value. This section covers how to combine conditionals with loops, plus two statements that only make sense inside loops: break (exit the loop now) and continue (skip to the next iteration).
Using if inside a loop
You can use if (and elif, else) inside a loop. The condition is checked on every iteration, so you can react differently to each item.
Example: Print only the even numbers from 1 to 10. Loop over the numbers and print only when the number is even (divisible by 2 with no remainder):
for number in range(1, 11):
if number % 2 == 0:
print(number)Each time through the loop, we check the condition. When it’s true, we print. When it’s false, we do nothing and move to the next number. Output: 2, 4, 6, 8, 10.
You can use any control flow you’ve learned inside a loop—if, elif, else. Loops and conditionals work together: “for each item, do this only when that’s true.”
The break statement
break exits the loop immediately. No more iterations run. Use it when you’ve found what you’re looking for or when a condition says “stop.”
Example: Search for the number 7 and stop as soon as you find it:
number_we_are_looking_for = 7
current_number = 1
while current_number <= 10:
if current_number == number_we_are_looking_for:
print(f"Found the number: {current_number}")
break
print(f"Checking number: {current_number}")
current_number += 1When current_number is 7, we print the message and hit break. The loop ends right there—we don’t check 8, 9, or 10. Without break, the loop would keep going to 10.
The continue statement
continue skips the rest of the current iteration and jumps to the next one. The loop keeps running; you just skip one pass. Use it when you want to ignore certain items but keep processing the rest.
Example: Print only even numbers by skipping odd ones with continue:
for number in range(1, 11):
if number % 2 != 0:
continue
print(number)When the number is odd, we hit continue and skip the print. When it’s even, we don’t hit continue, so we run the print. Result: 2, 4, 6, 8, 10—same as the first example, but this time we used continue to skip the odd numbers instead of an if around the print.
In short: break means “exit the loop.” continue means “skip the rest of this iteration and go to the next.”
Summary
- Use
if,elif, andelseinside a loop to run code only when a condition is true on that iteration. breakexits the loop early;continueskips to the next iteration.- Together they let you build loops that react to conditions and stop or skip when you need to.