What are break, continue, and pass statements in Python?


break, continue, and pass are control flow statements in Python. break exits a loop prematurely, continue skips to the next iteration of the loop, and pass does nothing but is used as a placeholder to write code that we can complete later without causing errors in the meantime.

How break, continue, and pass work

In Python, loops are essential for automating repetitive tasks, but sometimes, we need more control over the flow of these loops. Imagine we’re processing a list of customer orders. Some orders may be flagged as invalid, others might be incomplete but should be skipped, and we might want to leave a placeholder for orders that require further review. To handle these scenarios effectively, we can use break, continue, and pass to control the flow of our loop:

  • break: If an invalid order is detected, it stops processing the orders altogether.

  • continue: It skips over incomplete orders and moves to the next one.

  • pass: This is a placeholder for future logic, such as additional checks for flagged orders.

The break statement in Python: Exiting a loop early

The break statement allows us to exit a loop prematurely when a certain condition is met. Once break is executed, the loop stops, and the control moves to the next line after the loop.

Let’s look at an example that demonstrates the break statement in a for loop.

# List of passwords
passwords = ["password123", "12345", "securePassword!", "guest", "qwerty", "letmein", "123password"]
# A valid password we're looking for
valid_password = "securePassword!"
# Loop through passwords to find the correct one
for password in passwords:
if password == valid_password:
print("Valid password found: " + password)
break # Exit the loop once we find the valid password
print(password + " is not the correct password.")

In the example above, the loop iterates through a list of passwords. When it encounters the correct password ("securePassword!"), it prints a success message and breaks out of the loop. This prevents unnecessary checks against the remaining passwords, optimizing performance.

Try this yourself:

Try commenting out line 11 to see how the loop keeps checking against the remaining passwords and keeps printing that it's not the correct password. Ideally, once the correct password is found, we should not check for the remaining passwords.

Let’s see the flowchart below for a pictorial representation of how the use of break just lets us exit the loop whenever we want:

The break statement allows one to exit a loop early

The continue statement in Python: Skipping to the next iteration

The continue statement allows us to skip the rest of the current iteration and move directly to the next one. This is useful when we want to ignore certain values but still complete the loop.

Let’s look at an example that demonstrates the continue statement in a for loop:

# Example of the continue statement in a for loop:
for i in range (12):
if i % 2 == 0:
continue
print(i)

In the example above, only the odd numbers are printed because all even numbers loop again (due to the continue statement) and skip the respective print statement.

Try this yourself:

  • Change the condition from i % 2 == 0 to i % 3 == 0 and observe how the output changes.

  • Instead of skipping numbers, modify the code to print a message like "Skipping number x" for skipped values.

Let’s see the flowchart below for a pictorial representation of how the use of continue skips the current iteration of the loop and proceeds to the next:

Given a specified exception, the continue statement allows one to remain within the looping cycle

The pass statement in Python: A placeholder for future code

The pass statement acts as a placeholder that does nothing. It’s a simple way to tell the interpreter, “I know this is a part of my code, but I’ll fill it in later.” It allows us to write code that we can complete later without causing errors in the meantime.

The pass statement is useful for writing code skeletons. It helps avoid errors when parts of the code are yet to be implemented. We can use it to keep our code syntactically correct while we develop our program.

Let’s look at an example that demonstrates the pass statement.

def add_task():
pass # Functionality for adding tasks will be implemented later
def remove_task():
pass # To be implemented later
def list_tasks():
tasks = ["Buy groceries", "Clean the house", "Pay bills"]
for task in tasks:
print(task)
# Currently, only the list_tasks function is fully implemented
list_tasks()
# You can call add_task() and remove_task(), but they do nothing for now
add_task()
remove_task()

In this task management system, the pass statement is used in the add_task and remove_task functions. This indicates that while these functions are defined, their functionality will be added later. Using pass allows the code to run without syntax errors, enabling developers to build out their program structure incrementally.

Example using Python break, continue, and pass

Consider a scenario where you have an automated system to approve user registrations. If the input contains a specific keyword, you either skip further checks (continue), require extra approvals (pass), or terminate the check process (break).

user_inputs = ["approve", "review", "flag", "discard", "approve"]
for action in user_inputs:
if action == "discard":
break
elif action == "flag":
pass # Placeholder for future logic
elif action == "review":
continue
print("Processed: " + action)
print("End of processing")
Quiz yourself

Refer to the code above and answer the following questions.

1

Why doesn’t review get printed when action is review?

A)

The loop is terminated.

B)

The code below the continue statement is executed.

C)

The loop skips to the next iteration without printing anything.

D)

The variable action is set to a different value.

Question 1 of 30 attempted

Key takeaways

The break, continue, and pass statements in Python allow greater control and flexibility in coding by permitting useful exceptions to a program’s architecture.

  • break: We use it to stop a loop as soon as a specific goal is achieved, saving processing time and resources.

  • continue: We use it to skip unnecessary iterations and focus only on relevant data, improving loop efficiency.

  • pass: We use it to serve as a placeholder for code that we plan to implement later, ensuring the program remains syntactically correct without affecting execution.

Using these control statements effectively helps us manage loops and code blocks with precision, making our code more efficient and readable.

Become a Python developer with our comprehensive learning path!

Ready to kickstart your career as a Python Developer? Our "Become a Python Developer" path is designed to take you from your first line of code to landing your first job.
This comprehensive journey offers essential knowledge, hands-on practice, interview preparation, and a mock interview, ensuring you gain practical, real-world coding skills. With our AI mentor by your side, you’ll overcome challenges with personalized support, building the confidence needed to excel in the tech industry.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


What's the difference between break and continue in Python?

break exits the loop entirely whereas continue skips to the next iteration of the loop.


Can the pass statement be used in loops?

Yes, pass can be used in both for and while loops, serving as a placeholder where code will be implemented later.


How does the break statement work in nested loops?

In nested loops, the break statement only terminates the loop in which it is placed. Once break is encountered, the current loop is exited immediately, and control moves to the next statement outside that loop. If the break statement is in the outer loop, it terminates the entire loop structure, immediately exiting the outer and inner loops. This stops all iterations, and the control moves to the next statement after the outer loop.


What is the difference between break and return when used in function scopes?

The break statement is used to exit loops early, stopping the iteration but keeping execution within the enclosing function. On the other hand, the return statement exits the entire function, immediately ending its execution and optionally returning a value to the caller.


Free Resources