Python else after for/while loop explained with Example

Python else after for/while loop explained with Example

For most of the programming languages like C/C++, Java…, else-statement is coupled with if-statement. The else-statement can be used only with the if-statement.

This is not the case with Python. As usual, you are free to use else-statement with if-statement. You can also use else-statement after for or while loop.

But, how does it work?

In Python, if you are using else statement after the loop…

The else-block will not be executed if the break statement is executed inside the loop.

This is really a tricky and exceptional concept. There are many questions asked in job interviews based on this concept.

As a part of this tutorial, you will learn using else-statement after for and while loop in Python.

Let’s take some examples.

Example: Python for else

The syntax is simple. Write else-block just after for loop.

for i in range(0,5):
    print(i)

else:
    print("inside else")

What is the output of this program?

Output:

0
1
2
3
4
inside else

Here else-statement is getting executed as there is no break statement inside the for-loop.

We are using range() method to iterate over for-loop.

Now, let’s add break statement inside for loop.

for i in range(0,5):
    if i==3:
        break;
    print(i)

else:
    print("inside else")

Execute the program and print the output.

Output:

0
1
2

When i==3 inside for loop, the break statement will be executed. Control will come out of the for-loop and will not execute the else-block.

Now consider while loop.

Example: Python while else

You can also use else statement with while loop.

i=0
while i<5:
    print(i)
    i=i+1

else:
    print("inside else")

What is the output of this program?

Output:

0
1
2
3
4
inside else

The else-block is executed as there is no break statement inside the while loop.

Now we are adding break statement inside the while loop.

i=0
while i<5:
    if i==3:
        break
    print(i)
    i=i+1

else:
    print("inside else")

Run this program again and see the output.

Output:

0
1
2

As break statement has occurred inside the while-loop, else-block is not executed.

This is a little confusing for many of us. Just to remember- when there is a break, there is no else. When there is no break, there is else.

Note: Python for else and Python while else statements work same in Python 2 and Python 3. You can try running this program in different Python versions.

Related tutorials:

Any doubt? Write in the comment.

Leave a Reply

Your email address will not be published. Required fields are marked *