break
exits the loop entirely whereas continue
skips to the next iteration of the loop.
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.
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.
break
statement in Python: Exiting a loop earlyThe 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 passwordspasswords = ["password123", "12345", "securePassword!", "guest", "qwerty", "letmein", "123password"]# A valid password we're looking forvalid_password = "securePassword!"# Loop through passwords to find the correct onefor password in passwords:if password == valid_password:print("Valid password found: " + password)break # Exit the loop once we find the valid passwordprint(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:
continue
statement in Python: Skipping to the next iterationThe 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:continueprint(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
toi % 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:
pass
statement in Python: A placeholder for future codeThe 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 laterdef remove_task():pass # To be implemented laterdef list_tasks():tasks = ["Buy groceries", "Clean the house", "Pay bills"]for task in tasks:print(task)# Currently, only the list_tasks function is fully implementedlist_tasks()# You can call add_task() and remove_task(), but they do nothing for nowadd_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.
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":breakelif action == "flag":pass # Placeholder for future logicelif action == "review":continueprint("Processed: " + action)print("End of processing")
Refer to the code above and answer the following questions.
Why doesn’t review
get printed when action
is review
?
The loop is terminated.
The code below the continue
statement is executed.
The loop skips to the next iteration without printing anything.
The variable action
is set to a different value.
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.
Haven’t found what you were looking for? Contact Us