The for...else Statement in Python

In programming, we use loops for iterating over different types of objects. The for loop is one of the most widely used loops due to its simplicity.

Python has a very interesting feature associated with the for loop. It allows us to use the else statement with the for loop for combining condition execution and iteration. The else keyword is generally used in if-else statements, where we use it to execute some commands when the if condition returns false.

However, this is not the case when we work with the for loop in Python. Statements in the else block are executed based on a completion clause when the loop is over, given that the loop does not encounter the break statement in any of its iterations. The break statement is used to break out of a loop. If no break statement is encountered, then the else block statements are also executed after the loop.

If the continue statement is encountered, then the else statement gets executed. This is because the continue statement forces the next iteration. It does not break out the loop.

See the following code.

for i in range(3):
    if(i > 5):
        break
else:
    print("Else Statements")
    
for i in range(3):
    if(i > 1):
        print("Break")
        break
else:
    print("Else Statements")
    
for i in range(3):
    if(i > 1):
        continue
else:
    print("Else Statements after Continue")

Output:

Else Statements
Break
Else Statements after Continue

Now, the use of the for...else is not received well by many experienced programmers since it may lead to confusion over the use of the else keyword. However, it still has some useful applications in Python.

For example, we can use it if we are searching for an element in a list and wish to know whether it is present in the list or not. The following code snippet implements this.

a = 15
lst = [10,5,6,8,9,7,5,11]
for i in lst:
    if(i == 15):
        print("Found")
        break
else:
     print("Not Found Loop Over")   

Output:

Not Found Loop Over

The use of the else keyword is not limited to the for loop and can be used with the while loop also in Python.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Python Statement

  • Python Multiple if Statements on One Line
  • Nested try...except Statements in Python
  • Python Multi-Line if Condition
  • if...else in One Line Python