Use of else block with Python loops

An awesome feature that most programming languages do not offer

Sagun Raj Lage
The Startup

--

“An else block can exist only when an if block exists before it.”

As a programmer not belonging to Python background, I was a strict follower of this rule. But I was left awestruck and confused after I saw one of my friends’ Python code that used an else block after a for loop. So, I performed some research and found that Python provides a feature, that allows us to use an else block with for and while loops. The else block after a for or while loop is executed only when that loop is not terminated by a break statement. I’m very excited to show you how it works.

else block with a for loop

To demonstrate the execution of an else block after a for loop, let’s consider the following code:

The output of the code given above would look like this:

0
1
2
3
4
5
6
7
8
9
Printed because there was no break in for loop

--

--

Sagun Raj Lage
The Startup

Author of Getting Started with WidgetKit (2021) | Research Associate at UGA Savannah River Ecology Laboratory | iOS Engineer | Full Stack Engineer