Using break and continue in Python. Python is a versatile and intuitive programming language used in a variety of fields, from web development to data analysis and artificial intelligence. Having a strong grasp of control flow statements like break
and continue
can enhance your coding efficiency and problem-solving skills. In this article, we will understand these two statements, their functionality, and how they can be used effectively in loops.
Table of Contents
break Statement in Python
The break
statement in Python is used to exit or break out of a loop when a specific condition is met. This means that it stops the execution of the loop and proceeds to the next line of code outside the loop.
break Syntax in Python
while condition:
# code
if break_condition:
break
# more code
Or,
for item in iterable:
# code
if break_condition:
break
# more code
Example of break in Python
Imagine you are searching for a particular value in a list. Once you find a value, there is no need to continue looping through the rest of the list.
numbers = [1,3,5,2,4,7,6,8]
for n in numbers:
if n == 2:
print("Found the number 2")
break # exit the loop
print("outside the loop")
In this example, once the number 2 is found, the break
the statement exists in the loop, and the program continues with the next line, printing “outside the loop”.
continue Statement in Python
The continue
on the other hand, the statement in Python is used to skip the rest of the code inside a loop for the current iteration only. The loop does not terminate but continues on with the next iteration.
continue Syntax in Python
while condition:
# code
if continue_condition:
continue
# more code
Or,
for item in iterable:
# code
if continue_condition:
continue
# more code
Example of continue in Python
Let’s say we want to print all numbers from 1 to 5, except for number 3.
for n in range (1,6):
if n == 3:
continue
print(n)
In this example, when n
is 5, the continue statement is executed. This skips the print(n)
statement for this iteration only, and the loop continues with the next number.
Practical Use Cases for break and continue
- Filtering Data: We can use
continue
to filter out specific values from the data set while iterating, making it very useful for data-cleaning tasks. - Early Loop Termination: We can use
break
it to exit a loop as soon as a condition is met. This is helpful in scenarios where continuing the loop is unnecessary. - Nested Loop: Both
break
andcontinue
can be particularly useful in nested loops, where we have to skip some iteration or exit from the inner loop based on certain conditions.
In conclusion, break
and continue
are powerful Python keywords that, when used correctly, can make your loops more efficient.
Happy Coding & Learning
4 thoughts on “Using break and continue in Python”