Else Conditional Statement with for Loop in Python

Today we will learn else conditional statement with for loop in Python.

In other programming languages no matters its procedural or object-oriented language, else is restricted to be used with if statement only. But in Python, we can actually use the else conditional statement with the for loops.

Remember, only when the FOR loop terminated with the BREAK statement, then this ELSE statement will run after loop execution.

SYNTAX:

for i in range(x):
    #Statements
else:
    #Statements

FlowChart:

Else Conditional Statement with for Loop in Python

For Example:

for i in range(5):
    print(i)
else:
    print("Printed because there is no Break Statement in the For loop")

OUTPUT:

0
1
2
3
4
Printed because there is no Break Statement in the For loop

The Else statement worked because this for loop didn’t execute the break statement or it didn’t have any break statement.

But in this case:

for i in range(5):
    print(i)
    break
else:
    print("Printed because there is no Break Statement in the For loop")

OUTPUT:

0

It didn’t execute the else statement as the for loop is terminated with the break statement.

This kind of else statement works perfectly whenever there is an if condition inside the for loop.
E.g. In the below example the else statement will only execute whenever there is an even number in a list. If there is no even number then it will not execute the else statement.

def even_Number(l):
    for num in l:
        if num % 2 != 0:
            print("List don't have any even number")
            break
    else:
        print("List contain even numbers")
        
list1 = [1, 3, 4]
list2 = [2, 4, 6]

even_Number(list1)
even_Number(list2)

OUTPUT:

List don't have any even number
List contain even numbers

Also read: Ternary Operator Without Else In Python

Leave a Reply

Your email address will not be published. Required fields are marked *