Python Break, Continue and Pass: Python Flow Control

Python Flow Control Python break, continue, and pass Cover Image

In this tutorial, you’ll learn about Python flow control, using the break, continue, and pass statements. Each of these statements alter the flow of a loop, whether that be a Python while loop or a for loop. Understanding these flow control statements, such as Python break, allows you to gain control over your Python loops, by allowing you to easily skip over certain parts of the flow, based on a condition.

In this guide, you’ll learn the nuances of each of these statements. Knowing how these work allow you to break a loop entirely, skip over an item, or simply pass an action. Because we use loops to repeat an action a certain number of times, being able to add conditions to your loops and control their behaviour (or, flow) allows you to build more complex loops.

The Quick Answer: Use Python break, continue and pass

# Understanding Python Flow Control
break       # End the loop entirely
continue    # End the current iteration
pass        # Pass the statement but keep in the iteration

How do Python Loops Work?

Python loops allow us to automate and repeat tasks either a defined number of times or while a condition is met.

For example, Python for loops are examples of definite iteration, meaning they repeat a certain number of times. Python while loops, on the other hand, are examples of indefinite iteration, meaning that they repeat an indefinite number of times, while a given condition remains true.

Python For Loop Example

A Python for loop is a definite iteration, meaning that an action is repeated for a set number of times. Let’s take a look at a very simply example:

# A Simple Python for loop
for i in range(3):
    print(i)

# Returns:
# 0
# 1
# 2

Similarly, we can loop over an iterable item such a list:

# A Simple Python for loop
for item in ['welcome', 'to', 'datagy']:
    print(item)

# Returns:
# welcome
# to
# datagy

To learn more about Python for loops, check out my in-depth tutorial on them.

Python While Loop Example

While Python for loops occurred a definite number of times, Python while loops repeat an indefinite number of times. They repeat as often as a condition remains true. This can even mean that a while loop repeats an infinite number of times, if a condition is never false.

Let’s take a look at a simple example:

# A Simply Python while loop
i = 0

while i < 3:
    print(i)
    i += 1

# Returns:
# 0
# 1
# 2

Here, we use the augmented assignment operator to increment a value in Python, each time a while loop iterates. This allows us to end a while loop.

How Else Can We End Loops? Python flow control statements such as break, pass, and continue allow us to control how a Python loop works. Rather than relying on definite or indefinite iteration, we can use these control statements to change the behaviour (or even entirely stop) the flow of a loop.

In the next three sections, you’ll learn how to use these control statements to modify the behaviour of your loops.

Python Break Statement: End a Loop Entirely

The Python break statement breaks a the flow of an entire loop. This means that the entire loop is terminated and no further iteration of the loop will occur. This means that the loop will terminate and your program will move on to any statements that follow the loop.

We can also place break statements into nested loops. When placed into an inner loop, the break statement only causes the inner loop to be terminated, while the outer loop will continue to run.

The image below illustrates the logical process flow of a Python break statement.

Python Break Statement
The Python Break Statement Flow Control in a Loop

Let’s now take a look at an example of the Python break statement.

Python Break Statement Example

We can insert an if statement into a Python while loop. If our condition evaluates to a particular condition, we can break the loop, even if normally the loop would continue.

Let’ see what this looks like:

# An Example of the Python break Statement
i = 0
while i <= 5:
    if i == 3:
        break
    else:
        print(i)
        i += 1
print('Program is complete!')

# Returns:
# 0
# 1
# 2
# Program is complete!

We can see that while our values still had not reached the value of 5 (meaning the outer condition of the while loop), the while loop encountered the break statement. This caused the entire loop to end, causing the program to move onto the next statements of printing 'Program is complete!'.

In the next section, you’ll learn about the Python continue statement, which allows you to pass over an entire iteration but continue a loop.

Python Continue Statement: End an Iteration

The continue statement tells Python to continue from the next iteration, without fully breaking the flow of the loop. What this means is that the entire iteration is skipped over following the meeting of the continue statement.

This can be incredibly helpful when you’re reading in files or data. This is because if an erroneous iterable is encountered, we can simply ask Python to continue with the processing, but skip that particular item.

The flow chart below demonstrates the logical flow of operations when a loop encounters a continue statement.

Python Continue Statement
The Python Continue Statement Flow Control in a Loop

We can easily see the differences between this and the break statement, as the loop is able to continue.

Python Continue Statement Example

The continue statement can be easily demonstrated with an example. Let’s take a look at a for loop:

# An Example of the Python continue Statement
for word in ['welcome', 'to', 'the', 'datagy']:
    if word == 'the':
        continue
    else:
        print(word)

# Returns:
# welcome
# to
# datagy

We can see that when Python encountered the condition of our word being equal to 'the', that the continue statement caused the flow to pass to the next iteration.

But what about Python while loops? Here we actually need to be careful. Consider the example below:

# Considering a continue Statement in a While Loop
i = 0
while i <= 5:
    if i == 3:
        continue
    else:
        print(i)
        i += 1
print('Program is complete!')

What do you think would happen with this code? The code would actually never complete running. This is because the iterator i would never increase in value. Once the code hits the condition of i==3, the code would hit the continue statement. This causes the loop to start again, with the value still being 3.

In order to fix this, we can either place the increment prior to the if statement, or nest it prior to the continue statement.

Let’s see how we can fix our code:

# An Example of the Python continue Statement
i = 0
while i <= 5:
    if i == 3:
        i += 1
        continue
    else:
        print(i)
        i += 1
print('Program is complete!')

# # Returns:
# 0
# 1
# 2
# 4
# 5
# Program is complete!

We can see that in this case, the while loop actually terminates when the value of 5 is reached. The value of 3 is also never printed, as that value encounters the continue statement.

The example above shows how careful we need to be with indefinite iterations (while loops). Because these can truly run indefinitely, we need to ensure that our program is safe-guarded against memory leaks.

In the next section, you’ll learn about the final flow control, the Python pass statement.

Python Pass Statement: Pass Over a Condition

In this final section, you’ll learn about the Python pass statement. The pass statement, on the surface, may appear very similar to the continue statement. The key difference is that the pass statement simply passes over a given condition, but does not immediately move on to the next iteration of our loop.

This has the benefit of handling an event, such as an exception, while still maintaining the entire loop.

Python Pass Statement
The Python Pass Statement Flow Control in a Loop

This is best explained using an example, especially one that compares the continue and pass statements.

Python Pass Statement Example

Let’s consider the pass statement in comparison to the continue statement. We’ll create the same for loop that loops over the values from 0 through 5. If the value is 3, the program will either continue or pass. Finally, the value is printed.

Let’s see what the results look like:

# Compare the continue and pass Statements in Python
for i in range(6):
    if i == 3:
        continue
    print('continue Example value: ', i)

for i in range(6):
    if i == 3:
        pass
    print('pass Example value: ', i)

# Returns:
# continue Example value:  0
# continue Example value:  1
# continue Example value:  2
# continue Example value:  4
# continue Example value:  5

# pass Example value:  0
# pass Example value:  1
# pass Example value:  2
# pass Example value:  3
# pass Example value:  4
# pass Example value:  5

We can see that while the continue statement prevented the value of 3 being printed, that the pass statement simply continued the entirety of the iteration.

This is an important distinction. It allows us to, for example, handle an event like an exception but still allow other pieces of code to occur. In fact, if we consider the example above where our while loop continued indefinitely without nesting our else condition, we could handle this problem better.

This code will continue (pardon the pun!) to fail:

# Considering a consider Statement in a While Loop
i = 0
while i <= 5:
    if i == 3:
        continue
    print(i)
    i += 1
print('Program is complete!')

# Returns:
# 0
# 1
# 2

Meanwhile, if we use a pass statement, the code will run successfully:

# Considering a pass Statement in a While Loop
i = 0
while i <= 5:
    if i == 3:
        pass
    print(i)
    i += 1
print('Program is complete!')

# Returns:
# 0
# 1
# 2
# 3
# 4
# 5
# Program is complete!

Knowing the differences in these implementations means that one program will run successfully, while the other will cause issues.

Conclusion

In this post, you learned how to use the Python flow control statements, break, continue, and pass. You learned the key differences between these statements, allowing you how to choose which statement will meet your needs best. You also learned some nuances that may cause significant issues in your program if a code runs through to infinity.

To learn more about flow control statements in Python, check out the official documentation here.

Additional Resources

To learn about related topics, check out these articles:

Tags: