To handle circumstances where you would like to completely exit a loop when an outside condition is met or skip a portion of the loop and begin the following emphasis, Python offers the 🔴 break, 🚫 pass, and ➡️ continue commands.
Break Statement in Python
Imagine you work for a delivery company that needs to deliver packages to multiple customers. Your task is to create a program determining which packages to deliver based on their priority.
To do this, you have a list of packages with their priorities. The priority is represented as a number, where a higher number means higher priority. Your program needs to iterate through the list of packages and deliver the ones with the highest priority first.
However, your delivery truck has a limited capacity and can only carry a certain number of packages at once. If there are too many high-priority packages, you may be unable to fit them all in the truck. This is where the "break" statement comes in handy.
In Python, the "break" statement is used to exit a loop prematurely. In this case, you can use it to stop iterating through the list of packages as soon as you've filled up the truck with the highest-priority packages.
packages = [("Package A", 5), ("Package B", 8), ("Package C", 3), ("Package D", 9), ("Package E", 7)] max_priority = 8 # the maximum priority that can fit in the truck truck_capacity = 2 # the maximum number of packages that can fit in the truck packages_to_deliver =  for package in packages: if package >= max_priority: packages_to_deliver.append(package) if len(packages_to_deliver) == truck_capacity: break print("Packages to deliver:", packages_to_deliver)
In this code, the "for" loop iterates through each package in the list. If the package has a priority greater than or equal to the maximum priority that can fit in the truck, it is added to the list of packages to deliver.
However, as soon as the number of packages to deliver reaches the truck capacity, the "break" statement is executed, and the loop is exited prematurely. This prevents the program from adding more packages to the list since they wouldn't fit in the truck anyway.
Finally, the program prints out the list of packages to deliver.
Importance of Break Statement
The syntax for break statements in a for loop
for loop if condition: break
The syntax for break statement in a while loop
while expression: #some code if condition: break #some more code #outside the loop
Implementation of Break Statement in Python
Example of a for loop that uses a break statement:
for x in range(5): if x == 3 or x>4: break print(x)
This code will iterate through the numbers 0-4 (inclusive) and print each one to the console. If the number is 3 or greater than 4, the loop will break, and the code will end.
Pass Statement in Python
In Python, the pass statement is used as a placeholder for code that still needs to be implemented. It is a null operation, meaning that it does nothing. It can also be used as a placeholder for loops or conditional statements that still need to be fully defined.
Why do we Use Pass Statement?
A Pass statement allows us to have an empty loop or an empty conditional clause, which are syntactically valid but don't do anything. This is particularly useful when we need a loop or conditional statement as part of our code but want to wait to execute any code within it.
for i in range(10): if i == 5: pass else: print(i)
This code will loop through every number from 0 to 9 and print each number except for 5. The pass statement here is a placeholder, as it is syntactically valid but does not execute any code. If the if statement evaluates to True, meaning that the value of i is 5, then the pass statement is executed instead of any code. This allows the loop to continue without any errors.
Temporary Uses of Pass Statement
The pass statement can be used to initialize code that could later be used. Although it may seem ridiculous to use the pass statement in code that will eventually be removed, it helps to speed up development in the early stages.
Where one function calls another to do a task. Nevertheless, the issue here is that you must be made aware of how your calling function operates. Use the pass statement as a result.
def fun1(args): # some code fun2(): # some more code return values def fun2(args2): pass # TODO
Although func2 is now idle, it enables error-free operation and testing of fun1. When you only want to comprehend the structure of the code before delving into its nuances, the pass statement has another application. The pass statement is being used in this temporary instance. Moreover, it has permanent use cases like:
The try... except block is used in Python to handle errors ⚠️. When an error occurs 🤯, you might not always want to take any action :man_shrugging:. You may then employ the pass statement . I'll give you an illustration 📚.
def ensure_nonexistence(filename): try: os.remove(filename) except FileNotFoundError: pass
The above function deletes the specified file and doesn't throw an error if the file doesn't exist. You need not take any action if the file you wish to delete doesn't exist. You may thus only utilize the pass statement when the FileNotFoundError is triggered.
Continue Statement in Python
The continue statement in Python is used to skip the rest of the code inside a loop for the current iteration only. It causes the loop to immediately jump to the next iteration, skipping any code in between.
Example of continue statament:
i = 0 while i < 10: print(i) i += 1 if i == 5: continue
When the value of the variable i reaches 5, the continue statement is executed, which causes the loop to start again from the beginning without executing the rest of the code in the loop block. The output of this code will be the numbers 0 to 9, but with 5 skipped.
The "break" statement in Python is used to exit a loop prematurely. This statement causes the program to end the loop instantly, but the lines of code typed immediately following the body of the loop continue to run . In contrast, the "pass" statement in Python is used as a placeholder for code that is not yet implemented, and it does nothing. The pass statement is used to have an empty loop or an empty conditional clause, which is syntactically valid but doesn't do anything.
Answer: D. Does nothing and continues execution at the next statement.
Answer: D. Skips the current iteration and resumes execution at the next iteration.
Answer: B. Execution continues on the next statement after the loop.
def loop(): for i in range(1, 6): print(i) if i == 3: break
a. It prints the numbers from 1 to 6
b. It prints the numbers from 1 to 3
c. It prints the numbers from 3 to 6
d. It prints the numbers from 4 to 6
Answer: b. It prints the numbers from 1 to 3
Related Tutorials to watch
Top Articles toRead