Bytes

Break, Pass, and Continue Statements in Python

Module - 3 Loops and Iterations in Python
Break, Pass, and Continue Statements in Python

Overview:

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, Pass, and Continue Statements in Python-min.png

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[1] >= max_priority:
        packages_to_deliver.append(package[0])
        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

  • Python offers us a special purpose statement called break. It's important to remember that the break statement may only be used within for and while loops.
  • The break statement causes the program to instantly end the loop, but the lines of code typed immediately following the loop's body continue to run. Even if the while loop condition evaluates to True or, in the case of a for loop, the break statement will halt the loop.
  • Even if it meets the requirement, it will force the program's control to exit the for loop. While conducting a sequential search, for instance, the break statement is frequently utilized.
  • Consider using a for loop to find a specific element in a list of items.
  • A comparison condition will be included to see if the element is present. If the element is located, the loop will end without further exploration of the other elements.

The syntax for break statements in a for loop

for loop
        #some for block code
        if condition:
                break
        #some more code
#outside the loop

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.

Example:

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.

Example:

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:

Exception Catching:

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.

Conclusion

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.

Quiz

  1. What does the pass statement do in Python?
    1. Exits the current loop and resumes execution at the next statement.
    2. Skips the current loop and resumes execution at the next iteration. 
    3. Exits the current loop and resumes execution at the next iteration.
    4. Does nothing and continues execution at the next statement.

Answer: D. Does nothing and continues execution at the next statement.

  1. What does the continue statement do in Python?
    1. Exits the current loop and resumes execution at the next statement.
    2. Skips the current iteration and resumes execution at the next statement.
    3. Exits the current loop and resumes execution at the next iteration.
    4. Skips the current iteration and resumes execution at the next iteration.

Answer: D. Skips the current iteration and resumes execution at the next iteration.

  1. What happens when a break statement is encountered in a loop?
    1. Execution continues on the next iteration of the loop.
    2. Execution continues on the next statement after the loop.
    3. Execution immediately stops.
    4. Execution is transferred to the beginning of the loop.

Answer: B. Execution continues on the next statement after the loop.

  1. What does the following code do?
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

Online Python Compiler
Open Compiler
Recommended Courses
Masters in CS: Data Science and Artificial Intelligence
Course
20,000 people are doing this course
Join India's only Pay after placement Master's degree in Data Science. Get an assured job of 5 LPA and above. Accredited by ECTS and globally recognised in EU, US, Canada and 60+ countries.
Certification in Full Stack Data Science and AI
Course
20,000 people are doing this course
Become a job-ready Data Science professional in 30 weeks. Join the largest tech community in India. Pay only after you get a job above 5 LPA.

AlmaBetter’s curriculum is the best curriculum available online. AlmaBetter’s program is engaging, comprehensive, and student-centered. If you are honestly interested in Data Science, you cannot ask for a better platform than AlmaBetter.

avatar
Kamya Malhotra
Statistical Analyst
Fast forward your career in tech with AlmaBetter

Vikash SrivastavaCo-founder & CPTO AlmaBetter

Vikas CTO

Related Tutorials to watch

Top Articles toRead

AlmaBetter
Made with heartin Bengaluru, India
  • Official Address
  • 4th floor, 133/2, Janardhan Towers, Residency Road, Bengaluru, Karnataka, 560025
  • Communication Address
  • 4th floor, 315 Work Avenue, Siddhivinayak Tower, 152, 1st Cross Rd., 1st Block, Koramangala, Bengaluru, Karnataka, 560034
  • Follow Us
  • facebookinstagramlinkedintwitteryoutubetelegram

© 2023 AlmaBetter