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

PythonServer Side ProgrammingProgramming

One of the unique features of Python is ability to use else clause along with a loop. This feature is not seen in languages like C/C++ or Java.

Normally, the body of loop is repeatedly executed controlled by looping condition, after which statements after it start executing. In a Python loop, an else block will be executed after all iterations are over and before program exits the loop. Take a look at following example


for x in range(5):
print ('inside body of loop',x)
print ('else block of loop')
print ('outside loop')


Result shows else block executed before loop block is left

inside body of loop 0
inside body of loop 1
inside body of loop 2
inside body of loop 3
inside body of loop 4
else block of loop
outside loop
Published on 14-Feb-2018 20:08:31