All IT Courses 50% Off
Python Tutorials

Python Break, Continue and Pass Statements in Loops

Using loops are foundational concepts in Python and virtually every other programming language. In Python, the two kinds of loops are the for loop and the while loop. A for loop is used for parsing the elements in an iterator such as a string, list, tuple, set, etc one after the other. In contrast, the while loop is used to repeat a particular task if a condition is satisfied. 

But when working with loops, you can change how the iteration is done using the python break, continue and pass statement. In this tutorial, we will discuss how to use these statements to alter the behavior of both for loops and while loops in Python. By the end of this tutorial, you will learn:

  • Using the break Statement in Python
  • Using the break statement in For Loops
  • Using the Break Statement on While Loops. 
  • Using the break Statement with Nested Loops. 
  • The continue statement in Python
  • Using the continue Statement in while loops. 
  • Using the continue statement in nested loops. 
  • Using the pass statement. 

Without further ado, let’s jump into it. 

Using the break Statement in Python

The break statement is used to terminate a loop abruptly, based on another condition. When a break statement is used in a nested loop, the inner loop does not run anytime the specific condition is met. It terminates the inner loop and goes on to the outer loop. Let’s see how the break statement works for both for loops, while loops and nested for loops. 

Using the break statement in For Loops

Let’s say we have a list of names and we wish to stop the loop when a particular name is found, the break statement can be used for. Refer to the code example shown below.

names = ['Femi', 'Ken', 'David', 'Mah', 'Iliana', 'Hannah', 'Ahmed']
 
#loop over the list and terminates if the name 'David' is found.
for name in names:
    print (name)
    #set the condition for the break statement
    if name == 'David':
        print('David Found. Loop terminates here')
        break
Output:
Femi
Ken
David
David Found. Loop terminates here

As seen, the names after David were not printed. This is because the break statement stops the iteration once the name, David, is found. 

Now, let’s see how to do the same task with while loops. 

Using the Break Statement on While Loops. 

The code below shows how to perform the earlier task using while loops.

names = ['Femi', 'Ken', 'David', 'Mah', 'Iliana', 'Hannah', 'Ahmed']
i = 0
#loop over the list and terminates if the name 'David' is found.
while True:
    print(names[i])
    i += 1
    #set the condition for the break statement
    if names[i] == 'David':
        print('David Found. Loop terminates here')
        break
Output:
Femi
Ken
David Found. Loop terminates here

Note that when looping with the condition while True, it is an infinite loop. When using while loops in such a manner, it is critical to have some specified that would be required to terminate the loop. Else, the code will continue to run until you run out of memory or hit an error. 

Using the break Statement with Nested Loops. 

A nested loop in Python is a loop inside another loop. When you use the break statement inside the inner loop of a nested loop, the Python code terminates that loop and jumps to the outer loop. The outer loop keeps on running but terminates the inner loop whenever the condition is met. Let’s see an example.

list_1 = [1, 2, 3]
list_2 = ['a', 'b', 'c', 'd']
 
for x in list_1:
    for y in list_2:
        if y == 'c':
            break
        print(f"Outer loop: {x}, Inner loop: {y}")
Output:
Outer loop: 1, Inner loop: a
Outer loop: 1, Inner loop: b
Outer loop: 2, Inner loop: a
Outer loop: 2, Inner loop: b
Outer loop: 3, Inner loop: a
Outer loop: 3, Inner loop: b
Outer loop: 4, Inner loop: a
Outer loop: 4, Inner loop: b

Notice that the inner loop stops a ‘b’ without printing ‘c’ and ‘d’. The outer loop however prints all its elements. This is how the break statement works in nested loops. Now, we move on to the continue statement

The continue statement in Python

The continue statement is used to skip a particular iteration if a condition is met. Notice the difference between a continue statement and a break statement. While the break statement stops the loop, the continue statement only skips that iteration and moves on to the next element. Let’s see how to use the continue statement in Python.

names = ['Femi', 'Ken', 'David', 'Mah', 'Iliana', 'Hannah', 'Ahmed']
 
#loop over the list and skip the name 'David'.
for name in names:
    #set the condition for the continue statement
    if name == 'David':
        continue
    print(name)
Output:
Femi
Ken
Mah
Iliana
Hannah
Ahmed

You’d realize that the name ‘David’ was not printed. The same thing goes for a while loop.

Using the continue Statement in while loops. 

The continue statement can be used in while loops as well. See an example below.

number = 1
while number <= 7:    
    if number == 5:
        number += 1
        continue  
    print(number)
    number += 1
Output:
1
2
3
4
6
7
Notice that the number 5 was not printed. 

Using the continue statement in nested loops. 

We can apply the same principle in nested loops. Again, it skips the iteration for that loop and moves on with the next iteration.

list_1 = [1, 2, 3]
list_2 = ['a', 'b', 'c', 'd']
 
for x in list_1:
    for y in list_2:
        if y == 'c':
            continue
        print(f"Outer loop: {x}, Inner loop: {y}")
Output:
Outer loop: 1, Inner loop: a
Outer loop: 1, Inner loop: b
Outer loop: 1, Inner loop: d
Outer loop: 2, Inner loop: a
Outer loop: 2, Inner loop: b
Outer loop: 2, Inner loop: d
Outer loop: 3, Inner loop: a
Outer loop: 3, Inner loop: b
Outer loop: 3, Inner loop: d

Notice that this time, the outer loop, ‘d’ was printed. Only ‘c’ was skipped. This is how the continue statement works for nested loops. 

Using the pass statement. 

A pass statement is simply a null statement. It tells the Python interpreter to do nothing once encountered. It is typically used when creating a class or a function that you do not want to populate with codes yet. Using the pass statement would run the empty class or function without an error. 

The pass statement can as well be used in loops. As mentioned, it does nothing to a loop. But again, it is useful when you wish to run an empty loop without errors. See the code below.

for x in range(10):
    pass

Without the pass statement, the code would throw an error. However, the pass statement was used to create the loop without doing anything. 

To summarize, 

You have learned how to use the break continue and pass statement for loops in Python. Particularly, you discovered the use cases in for loops, while loops and nested loops. If you have any questions, feel free to leave them in the comment section and I’d do my best to answer them.

Facebook Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Related Articles

Back to top button
Close
Close