Loop Control Statements (break and continue)
In Python, loop control statements, such as break
and continue
, allow you to control the flow of loops and make them more flexible and efficient.
1. The break
Statement
The break
statement is used to prematurely terminate a loop, even if the loop condition is still true. It is commonly used to exit a loop when a certain condition is met. Here's how it works in a loop:
for item in sequence:
if condition:
break # Terminate the loop
For example, using break
to exit a for
loop when a specific condition is met:
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
if fruit == "cherry":
break
print(fruit)
In this case, the loop will stop as soon as it encounters the word "cherry," and "date" will not be printed.
2. The continue
Statement
The continue
statement is used to skip the rest of the current iteration and move to the next iteration of a loop. It is useful when you want to bypass certain elements or conditions and continue with the next iteration. Here's how it works in a loop:
for item in sequence:
if condition:
continue # Skip the rest of this iteration and continue with the next
For example, using continue
to skip printing an element in a for
loop:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
continue
print(num)
In this example, the continue
statement skips even numbers, and only odd numbers are printed.
3. Choosing Between break
and continue
- Use
break
when you want to exit the loop entirely when a specific condition is met. - Use
continue
when you want to skip the current iteration and move to the next iteration when a specific condition is met.
These loop control statements provide you with the ability to fine-tune the behavior of loops, allowing you to create more efficient and flexible code.