Python Continue and Break Statements
Python Continue and Break Statements
The break statement exits the loop, while continue skips to the next iteration without completing the current one. These statements give programmers finer control over how loops execute. Below is an explanation of each statement, along with its syntax and examples.
break Statement
The break statement stops loop execution immediately when a specified condition is met. When executed, it immediately terminates the loop, and the program continues with the first statement following the loop.
Syntax
break
Usage Example
Example: Using break in a for loop
# Example: Using break in a for loop
for number in range(1, 10):
if number == 5:
print("Breaking the loop at number", number)
break # Exit the loop when number equals 5
print(number)
# Output:
# 1
# 2
# 3
# 4
# Breaking the loop at number 5
Example: Using break in a while loop
# Example: Using break in a while loop
count = 0
while count < 10:
if count == 6:
print("Breaking the loop at count", count)
break
print(count)
count += 1
# Output:
# 0
# 1
# 2
# 3
# 4
# 5
# Breaking the loop at count 6
continue Statement
The continue statement jumps to the next loop cycle, ignoring the remaining code in the current iteration. The loop does not terminate; only the statements after continue within the loop are skipped for the current iteration.
Syntax
continue
Example: Using break in a for loop
# Example: Using continue in a for loop
for number in range(1, 10):
if number % 2 == 0: # Skip even numbers
continue # Skip the rest of the loop for even numbers
print(number)
# Output:
# 1
# 3
# 5
# 7
# 9
Example: Using continue in a while loop
# Example: Using continue in a while loop
count = 0
while count < 10:
count += 1
if count % 2 == 0: # Skip even numbers
continue
print(count)
# Output:
# 1
# 3
# 5
# 7
# 9
Key Differences Between break and continue
| Aspect | break |
continue |
|---|---|---|
| Effect on Loop | Terminates the loop entirely. | The continue statement skips to the next loop iteration. |
| Control Flow | Exits the loop immediately. | Proceeds to the next iteration. |
| Scope of Action | Ends the loop execution. | The continue statement bypasses remaining code and starts the next iteration. |
Summary
- Use
breakwhen you need to exit a loop before its natural termination condition is met. - Use
continueto skip certain iterations while keeping the loop running.
These statements are particularly useful in scenarios such as filtering data, breaking out of nested loops, or handling specific conditions dynamically.
Prefer Learning by Watching?
Watch these YouTube tutorials to understand Python Tutorial visually:
What You'll Learn:
- 📌 Python Break and Continue Statement | Python Tutorial!
- 📌 break and continue Statements in Pythonjg