Python for with else

for loop with else

A for loop may have an optional else block too. The else part is executed if the items in the iterating sequence used for the loop are exhausted. The break keyword may be used to stop the for loop.

Python allows us to include any number of for loops inside a specific for loop.

The keyword else in a for loop defines a piece of code to be performed when the loop is ended.
The loops are an essential part of all programming languages. Moreover, "for" loops are a significant part of Python. 
The "for; loops too have an else clause which most of us are unknown with. The else part executes after the loop usually finishes.
It implies that the loop did not find a break statement. This is very helpful once the user understands where to use them.

  • The else part will not be performed if the loop gets eliminated with a break statement.
  • When a loop does not catch a break statement, the else part will be performed once the loop has executed all its repetitions (indicating, after the loop has executed normally).

This type of else is helpful only when there is an if condition already inside the loop, depending on the loop variable.
This model is much better to know what's going on in our for loop after the condition else is checking whether it is true or not a break statement explicitly stopped the loop.


for x in range(6): print(x) else: print("Knowledge2life website")