How can I make sense of the else clause of Python loops?


In python programming the syntax of loops includes an optional else clause. This is a unique feature in python compared to the other programming languages.

In general, the body of a loop is repeatedly executed and controlled by a looping condition, after completing the iterations based on the condition the statements after it will start the executing. But in the Python loop, before the loop exits we can execute an else block after completing all the iterations.

Syntax

Following is the syntax of the else clause in the for loop

for variable_name in iterable:
    # statements
else:
    # statements

Following is the syntax of the else clause in the while loop

while condition:
    #statements
else:
    #statements

Example

Let’s take a look at the following example and see how the else clause works on for loop. In here, the statement of the else block is executed after the for loop has completed all its iterations.

for x in range(3):
    print('Inside the loop',x)
else:
    print('Else block of the loop')
print('Outside loop')

Output

Inside the loop 0
Inside the loop 1
Inside the loop 2
Else block of the loop
Outside loop

Example

Let us see an example for the else clause in the while loop

x = 3
while  x:
    print('Inside the loop',x)
    x -= 1
else:
    print('Else block of the loop')
print('Outside loop')

Output

Inside the loop 3
Inside the loop 2
Inside the loop 1
Else block of the loop
Outside loop

Note: In the above examples the result shows that the else block of the while loop is executed before exiting the loop. Note that the else clause will not be executed if the loop gets terminated by a break statement.

Example

In this example the for loop is terminated by using break, so that the else block is not executed.

for x in range(3):
    print('Inside the loop',x)
    break
else:
    print('Else block of the loop')
print('Outside loop')

Output

Inside the loop 0
Outside loop

Example

In this example while loop the else block is not executed because the loop is terminated by the break.

x = 3
while  x:
    print('Inside the loop',x)
    x -= 1
    break
else:
    print('Else block of the loop')
print('Outside loop')

Output

Inside the loop 3
Outside loop

Example

Let us see another example

def foo():
    for i in range(10):
        print('i: ',i)
        if i == 3:
            return 
    else:
        print("Completed successfully")

foo()

Output

i:  0
i:  1
i:  2
i:  3

Also the else block will not be executed if there is a return clause mentioned, because return leaves the function intermediately. As we see in the above output the else block is not executed because there is a return key mentioned in the loop.

Updated on: 23-Aug-2023

111 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements