Tutorial

How To Use Python Continue, Break and Pass Statements when Working with Loops

Updated on December 16, 2024
English
How To Use Python Continue, Break and Pass Statements when Working with Loops

Introduction

Using for loops and while loops in Python allows you to automate and efficiently repeat tasks. These loops are fundamental constructs in Python that enable you to iterate over sequences, such as lists, tuples, and strings, or to execute a block of code repeatedly based on a condition.

However, there are scenarios where you need more control over the flow of your loops. For instance, you might encounter a situation where you need to exit a loop prematurely, skip the current iteration, or simply have a placeholder for future code. Python provides three powerful statements to handle these cases: break, continue, and pass.

  • The break statement allows you to exit a loop entirely when a specific condition is met, effectively stopping the loop execution.
  • The continue statement lets you skip the rest of the code inside the loop for the current iteration and move on to the next iteration.
  • The pass statement is a null operation; it is used as a placeholder in loops, functions, classes, or conditionals where code is syntactically required but you have nothing to execute.

Understanding and utilizing these statements can significantly enhance your ability to manage loop control flow, making your code more efficient and easier to read. In the following sections, we will explore practical examples of how to use break, continue, and pass statements in Python loops.

Need to deploy a Python project and have it live quickly? Check out DigitalOcean App Platform and deploy a Python project directly from GitHub in minutes.

Prerequisites

You should have Python 3 installed and a programming environment on your computer or server. Suppose you don’t have a programming environment set up. In that case, you can refer to the installation and setup guides for setting up a local Python programming environment on your server appropriate for your operating system (Ubuntu, CentOS, Debian, etc.)

Break Statement

In Python, the break statement allows you to exit out of a loop when an external condition is triggered. You’ll put the break statement within the code block under your loop statement, usually after a conditional if statement.

Info: To follow along with the example code in this tutorial, open a Python interactive shell on your local system by running the python3 command. Then you can copy, paste, or edit the examples by adding them after the >>> prompt.

Let’s look at an example that uses the break statement in a for loop:

number = 0

for number in range(10):
    if number == 5:
        break    # break here

    print('Number is ' + str(number))

print('Out of loop')

The variable number is initialized at 0 in this small program. Then a for statement constructs the loop if the variable number is less than 10.

Within the for loop, an if statement presents the condition that if the variable number is equivalent to the integer 5, then the loop will break. You can refer to this tutorial on Using for() loop in Python to learn more about using the for loop.

Note: You can also refer to this tutorial on How to construct while loops in Python to learn more about looping in Python.

Within the loop is also a print() statement that will execute with each iteration of the for loop until the loop breaks, since it is after the break statement.

Let’s place a final print() statement outside of the for loop to know when you are out of the loop.

When you run this code, you will get the following output:

Output
Number is 0 Number is 1 Number is 2 Number is 3 Number is 4 Out of loop

This shows that once the integer number is evaluated as equivalent to 5, the loop breaks, as the program is told to do so with the break statement.

The break statement causes a program to break out of a loop.

Continue Statement

The continue statement allows you to skip over the part of a loop where an external condition is triggered, but to go on to complete the rest of the loop. The current iteration of the loop will be disrupted, but the program will return to the top of the loop.

The continue statement will be within the code block under the loop statement, usually after a conditional if statement.

Using the same for loop program as in the break statement section above, we’ll use a continue statement rather than a break statement:

number = 0

for number in range(10):
    if number == 5:
        continue    # continue here

    print('Number is ' + str(number))

print('Out of loop')

The difference in using the continue statement rather than a break statement is that our code will continue despite the disruption when the variable number is evaluated as equivalent to 5. Let’s review our output:

Output
Number is 0 Number is 1 Number is 2 Number is 3 Number is 4 Number is 6 Number is 7 Number is 8 Number is 9 Out of loop

Here, Number is 5 never occurs in the output, but the loop continues after that point to print lines for the numbers 6–10 before leaving the loop.

You can use the continue statement to avoid deeply nested conditional code or optimize a loop by eliminating frequently occurring cases you would like to reject.

The continue statement causes a program to skip certain factors that come up within a loop but then continue through the rest of the loop.

Pass Statement

When an external condition is triggered, the pass statement allows you to handle the condition without the loop being impacted in any way; all of the code will continue to be read unless a break or other statement occurs.

As with the other statements, the pass statement will be within the code block under the loop statement, typically after a conditional if statement.

Using the same code block as above, let’s replace the break or continue statement with a pass statement:

number = 0

for number in range(10):
    if number == 5:
        pass    # pass here

    print('Number is ' + str(number))

print('Out of loop')

After the if conditional statement, the pass statement tells the program to continue running the loop and ignore that the variable number evaluates as equivalent to 5 during one of its iterations.

You’ll run the program and get the following output:

Output
Number is 0 Number is 1 Number is 2 Number is 3 Number is 4 Number is 5 Number is 6 Number is 7 Number is 8 Number is 9 Out of loop

By using the pass statement in this program, you notice that the program runs exactly as it would if there were no conditional statements in the program. The pass statement tells the program to disregard that condition and continue to run the program as usual.

The pass statement can create minimal classes, or act as a placeholder when working on new code and thinking on an algorithmic level before hammering out details.

Conclusion

The break, continue, and pass statements in Python will allow you to use for loops and while loops more effectively in your code.

To work more with break and pass statements, you can follow the tutorial How To Create a Twitterbot with Python 3 and the Tweepy Library.

FAQs

How to use pass, continue, and break in Python?

  • pass: The pass statement does nothing; it is used as a placeholder when a statement is syntactically required but no action is needed. For example:
for i in range(5):
  if i == 3:
    pass  # Placeholder for future code
  print(i)
  • continue: The continue statement skips the rest of the code in the current iteration and moves to the next iteration of the loop. Example:
for i in range(5):
    if i == 3:
        continue  # Skip the current iteration when i == 3
    print(i)
  • break: The break statement exits the loop immediately, regardless of the iteration condition. Example:
for i in range(5):
    if i == 3:
        break  # Exit the loop when i == 3
    print(i)

How can you use break and continue statements in a for loop?

The break statement can be used inside a for loop to terminate it early when a specific condition is met. Example:

for i in range(10):
    if i == 5:
        break  # Exit the loop when i == 5
    print(i)

The continue statement skips the rest of the current iteration and moves to the next iteration. Example:

for i in range(10):
    if i % 2 == 0:
        continue  # Skip even numbers
    print(i)  # Only prints odd numbers

How do you continue a loop in Python after a break ?

Once a break statement is executed, the loop terminates, and the code after the loop is executed. If you want to “continue” a loop after breaking, you need to reinitialize the loop.

For Example:

for i in range(3):  # First loop
    if i == 1:
        break  # Break out of the loop when i == 1
    print(f"First loop iteration: {i}")

# Restarting the loop
for i in range(3, 6):  # Second loop
    print(f"Second loop iteration: {i}")

How can I use a break statement in my Python for loops?

The break statement is straightforward to use in a for loop to terminate it when a specific condition is met:

for i in range(5):
    print(f"Checking value: {i}")
    if i == 2:
        print("Condition met. Breaking out of the loop.")
        break  # Exit the loop immediately
print("Loop ended.")

How to code a loop in Python ?

In Python, loops can be written using for or while. Examples:

Using a for loop:

for i in range(5):
    print(i)  # Prints numbers from 0 to 4

Using a while loop:

count = 0
while count < 5:
    print(count)  # Prints numbers from 0 to 4
    count += 1

To learn more about using for loop and while loop in python, you can refer to the tutorials below:

What does pass do in a Python for loop?

The pass statement acts as a placeholder and performs no action. It’s often used when a block of code is syntactically required but hasn’t been implemented yet:

for i in range(5):
    if i == 3:
        pass  # Placeholder
    print(i)
Output
0 1 2 3 4

Does Python break exit all loops ?

No, the break statement only exits the innermost loop where it is executed. To exit nested loops, you can use additional control mechanisms, such as flags or functions. Example:

for i in range(3):
    for j in range(3):
        if i == 1 and j == 1:
            break  # Exits the inner loop
        print(f"i={i}, j={j}")
Output
i
=0, j=0 i=0, j=1 i=0, j=2 i=1, j=0

To exit all loops, you can use a flag or wrap the loops in a function and use return:

# Using a flag
flag = False
for i in range(3):
    for j in range(3):
        if i == 1 and j == 1:
            flag = True
            break
        print(f"i={i}, j={j}")
    if flag:
        break

# Using a function
def nested_loops():
    for i in range(3):
        for j in range(3):
            if i == 1 and j == 1:
                return  # Exit all loops
            print(f"i={i}, j={j}")

nested_loops()

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


Tutorial Series: How To Code in Python

Python is a flexible and versatile programming language that can be leveraged for many use cases, with strengths in scripting, automation, data analysis, machine learning, and back-end development. It is a great tool for both new learners and experienced developers alike.

About the authors

Default avatar

Sr Technical Writer

Senior Technical Writer @ DigitalOcean | 2x Medium Top Writers | 2 Million+ monthly views & 34K Subscribers | Ex Cloud Consultant @ AMEX | Ex SRE(DevOps) @ NUTANIX


Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
4 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Typo in example - blank line between break and print should not be there.

for number in range(10):
    if number == 5:
        break    # break here
    print('Number is ' + str(number))

is writing pass necessary? and what if we don’t write it?

exaplined quite simple, that’s nice; but you have a major error in your code: you modify the counter within the loop. Thr for with range automatically visits all values in the range. If you then increase the counter you will end up having only even numbers printed ;-)

Well done, Fully understood. Thanks for clarification. Have a nice day

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Become a contributor for community

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

DigitalOcean Documentation

Full documentation for every DigitalOcean product.

Resources for startups and SMBs

The Wave has everything you need to know about building a business, from raising funding to marketing your product.

Get our newsletter

Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

New accounts only. By submitting your email you agree to our Privacy Policy

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.