Use of else block with Python loops
An awesome feature that most programming languages do not offer
“An
else
block can exist only when anif
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