Else Clause in for and while Loops (Python)

In Python, the else clause can be used not only with if statements but also with for and while loops.

Syntax

while/for (condition):
block1
else:
block2

What is the purpose of the else clause in a loop?

In an iterative structure, the else clause specifies the code to execute once the loop completes all its iterations.

This block runs after the loop finishes its last iteration.

Example

a practical example of using else in a loop

The else clause in loops is a unique feature of Python.

It's not found in other programming languages like C or Java, where else is only used in conditional control structures.

In Python, you can use the else clause in both for and while loops.

Note: If the loop is prematurely terminated with a break statement, the else clause is not executed because the loop exits due to the forced termination.
if the loop is interrupted by break, the else clause does not execute

    Practical Examples

    Here are some practical examples of using the else clause in Python's looping structures.

    Example 1 (for)

    In this script, a for loop iterates 5 times.

    1. for x in range(1, 6):
    2. print(x)
    3. else:
    4. print("end")

    After the fifth iteration, the for loop executes the else clause.

    The program output is:

    1
    2
    3
    4
    5
    end

    The else clause is executed after the last iteration of the loop.

    It's like a final additional step.

    Example 2 (while)

    In this second script, a while loop runs for 5 iterations.

    1. x = 1
    2. while (x < 6):
    3. print(x)
    4. else:
    5. print("end")

    At the end of the fifth iteration, the while loop executes the else clause.

    The program output is:

    1
    2
    3
    4
    5
    end

    The functionality of the else clause is essentially the same in both for and while loops.

    And so on.

     
     

    Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

    FacebookTwitterLinkedinLinkedin
    knowledge base

    Loop Structures in Python

    Forced Interruptions and clauses