Chapter 6 – Flow of Control

Q #3 – Differentiate between break and continue statements using examples..
The break and continue statements in Python are control flow tools used to modify the execution of loops. Here’s a detailed differentiation between the two, along with examples for clarity.
Break Statement
The break statement is used to exit a loop entirely when a specific condition is met. Once break is executed, the control flow moves to the statement immediately following the loop.
Example 1 of Break
# Using break in a for loop
for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)
Output:
0
1
2
In this example, when i reaches 3, the break statement is executed, terminating the loop. As a result, numbers 3 and above are not printed.
Example 2: Searching for an Item:
In this example, we will search for a specific item in a list and exit the loop once the item is found.
# Searching for an item in a list
fruits = ['apple', 'banana', 'cherry', 'date', 'fig']
search_item = 'cherry'
for fruit in fruits:
if fruit == search_item:
print(f"{search_item} found!")
break # Exit the loop once the item is found
else:
print(f"{search_item} not found.")
Output:
cherry found!
Continue Statement
The continue statement is used to skip the current iteration of a loop and proceed to the next iteration. When continue is executed, the rest of the code inside the loop for that iteration is skipped.
Example of Continue
# Using continue in a for loop
for i in range(5):
if i == 3:
continue # Skip the current iteration when i is 3
print(i)
Output:
0
1
2
4
In this example, when i equals 3, the continue statement skips printing that value and moves on to the next iteration. Thus, only values 0, 1, 2, and 4 are printed.
Example 1: Filtering Even Numbers
# Filtering odd numbers from a list
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in numbers:
if num % 2 == 0:
continue # Skip even numbers
print(num)
Output:
1
3
5
7
9
Here, the continue
statement skips printing any even number in the list.
Summary of Differences:
Feature | Break Statement | Continue Statement |
Functionality | Exits the entire loop | Skips to the next iteration |
Control Flow | Moves to the statement after the loop | Moves to the next iteration within the loop |
Use Case | To terminate a loop based on a condition | To skip specific iterations based on a condition |
Summary of Usage
- Break is useful when you want to terminate a loop entirely based on a condition.
- Continue is beneficial when you want to skip certain iterations but continue looping through the rest.
These additional examples further illustrate how break and continue can be effectively used in various scenarios to control loop execution flow
NCERT Computer Science Chapter 6 Solutions Q 3