Back to course

Loop Control: `break` and `continue`

Python Programming: The 0 to Hero Bootcamp

Controlling Loop Execution

Python provides two keywords to change the flow of execution within a loop: break and continue.

1. break

The break keyword immediately terminates the current loop entirely (whether for or while) and execution jumps to the statement immediately following the loop.

Example: Searching for an Element

python numbers = [1, 5, 12, 8, 3, 15] search_target = 8 found = False

for num in numbers: if num == search_target: print(f"Target {search_target} found!") found = True break # Stop looping immediately

if not found: print(f"Target {search_target} not in list.")

2. continue

The continue keyword stops the current iteration of the loop and immediately moves to the next iteration.

Example: Skipping Even Numbers

python print("Odd numbers between 1 and 10:") for i in range(1, 11): if i % 2 == 0: # If it's even continue # Skip the print statement and go to next i

print(i)

Output: 1, 3, 5, 7, 9