Topic11: Pass, continue, break, and else in Python?


Loop Manipulation Using pass, continue, break, and else in Python

In Python, loops are used to execute a block of code repeatedly until a specific condition is met. However, sometimes we need more control over how the loop behaves  for example, to skip certain iterations, stop the loop early, or execute a block after the loop ends.

Python provides loop manipulation statements like pass, continue, break, and else to make loops flexible and powerful.

1. The pass Statement

The pass statement does nothing,  it’s a placeholder that helps maintain syntactic correctness when a statement is required but no action is needed.

Example:

for i in range(5):
    if i == 3:
        pass    # No action taken
    else:
        print("Value:", i)

Output:

Value: 0
Value: 1
Value: 2
Value: 4

Explanation:
When i == 3, Python executes pass and moves to the next iteration without doing anything.

2. The continue Statement

The continue statement skips the remaining code in the current iteration and jumps to the next iteration of the loop.

Example:

for i in range(6):
    if i == 3:
        continue
    print("Number:", i)

Output:

Number: 0
Number: 1
Number: 2
Number: 4
Number: 5

Explanation:
When i equals 3, the continue statement skips printing that value and resumes the loop with the next number.

3. The break Statement

The break statement immediately exits the loop, regardless of the loop condition.

Example:

for i in range(10):
    if i == 5:
        break
    print(i)

Output:

0
1
2
3
4

Explanation:
The loop stops when i == 5. The break statement ends the loop entirely, and no further iterations occur.

4. The else Clause in Loops

The else block in a loop runs only if the loop completes normally — that is, without encountering a break statement.

Example:

for i in range(5):
    print(i)
else:
    print("Loop completed successfully!")

Output:

0
1
2
3
4
Loop completed successfully!

Explanation:
Because there was no break, the else block executes after the loop finishes.

Example: Combining break and else

for i in range(5):
    if i == 3:
        print("Breaking the loop!")
        break
    print(i)
else:
    print("Loop ended normally.")

Output:

0
1
2
Breaking the loop!

Explanation:
Since the loop was terminated with break, the else part does not execute.


Summary

Loop control statements in Python   pass, continue, break, and else  provide fine-grained control over how loops execute. They make your programs more flexible, efficient, and readable by allowing selective skipping, controlled exits, and post-loop actions.

           ðŸ‘ˆ Previous                                                                                                 For Quiz Next👉


What is Machine Learning?

Comments

Popular posts from this blog

Topic1 :- What is Python Programming?

Topic2: -Why Python?

Topic7: What is Numpy?