Python

else condition with for loop ? | Python Facts

Yes, you can use else condition with for loop in Python.

There are lots of things which we are still unaware of. One of that is, using else condition with for loop.

In other language, else condition is restricted to use with if condition only but python provide us to use else with for loop.

What is else clause ?

else clause used with for loop executes after the for loop completes normally. Here normally, means the loop got exits out, not because of break statement.

Best Example – To search for even number

# For Python 3.x
def check_even_number(num): 
    for n in num: 
        if n % 2 == 0: 
            print ("num, list contains an even number") 
            break
    # This else executes only if break is not executed and loop terminated after all iterations are done. 
    else:      
        print ("num, list does not contain an even number") 
  
print("\nList A:")
check_even_number([1, 7, 8]) 

print ("\nListB:") 
check_even_number([1, 3, 5])
List A:
num, list contains an even number

List B:
num, list does not contain an even number

The common construct is to run a loop and search for an item. If the item is found, we break out of the loop using the break statement. There are two scenarios in which the loop may end. The first one is when the item is found and break is encountered. The second scenario is that the loop ends without encountering a break statement. Now we may want to know which one of these is the reason for a loop’s completion. One method is to set a flag and then check it once the loop ends. Another is to use the else clause.

In the following example, the else statement will only be executed if no element of the array is even, i.e. if statement has not been executed for any iteration and not encountered break  statement.

Therefore for the array [1, 7, 8] the if is executed in third iteration of the loop and hence the else present after the for loop is ignored. In case of array [1, 3, 5] the if is not executed for any iteration and hence the else after the loop is executed.