Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Break, Continue, and Pass Statements in Python


Introduction

Python provides special control statements like break, continue, and pass to alter the flow of loops or to handle cases where no action is required. This article explains these statements with examples.

Break Statement

The break statement is used to exit a loop prematurely when a specific condition is met. It is commonly used when the required task is complete, and there is no need to continue looping.

Example

The following example stops the loop when the number 3 is encountered:

    # Example of break statement
    for num in range(1, 6):
        if num == 3:
            break
        print(num)
        

Output:

    1
    2
        

Continue Statement

The continue statement is used to skip the current iteration and move to the next iteration of the loop. It is helpful when certain cases need to be ignored during looping.

Example

The following example skips the number 3 and continues with the rest of the loop:

    # Example of continue statement
    for num in range(1, 6):
        if num == 3:
            continue
        print(num)
        

Output:

    1
    2
    4
    5
        

Pass Statement

The pass statement is a placeholder that does nothing. It is used when a statement is syntactically required but no action is needed. It is often used during code development to indicate sections of the code to be implemented later.

Example

The following example demonstrates the pass statement in a loop:

    # Example of pass statement
    for num in range(1, 6):
        if num == 3:
            pass  # Placeholder for future code
        print(num)
        

Output:

    1
    2
    3
    4
    5
        

Comparison of Break, Continue, and Pass

Here is a summary of the differences between these statements:

Conclusion

The break, continue, and pass statements provide greater control over loops and program execution. Understanding their behavior is essential for writing efficient and readable code.



Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java