Using else conditional statement with for loop in python

In most programming languages ​​(C / C++, Java, etc.), the use of the else statement has been limited to conditional if statements. But Python also allows us to use the else clause with for loops.

The else block just after for / while is executed only when the loop is NOT terminated by a break statement.

The rest of the block is executed in the following Python 3.x program:

for i in range ( 1 , 4 ):

print (i)

else # Done because there is no break for

pri nt ( "No Break" )


 1 2 3 No Break 

In other Python 3.x programs, the block is NOT executed:

for i in range ( 1 , 4 ):

print (i)


else : # Not executed because there is a break

  print ( " No Break " )



This else type is useful only if the loop contains an if condition that somehow depends on the loop variable.

In the following example, the else statement will be executed only if none of the array elements are even, i.e. if the statement has not been executed for any iteration. Therefore, for the array [1, 9, 8], the if is executed in the third iteration of the loop and, therefore, the rest after the for loop is ignored. In the case of the array [1, 3, 5] if is not executed for any iteration and therefore the else after the loop.

# Python 3.x program for checking if the array consists of
even number

def contains_even_number (l):

for ele in l:

  if ele % 2 = = 0 :

print "list contains an even number" )



# This is still only done if break NEVER

Achieved # and the loop ends after all iterations.


print ( "list does not contain an even number" )

# Driver code

print ( "For List 1:" )

contains_even_number ([ 1 , 9 , 8 ])

print ( " For List 2: " )

contains_even_number ([ 1 , 3 , 5 ])


 For List 1: list contains an even number For List 2: list does not contain an even number 

As exercise predict the result of the next program.

count  = 0

while (count & lt;  1 ): 

  count = count + 1

print (count)


else :

print ( "No Break" )

This article is courtesy of Harshit Agrawal . If you are as Python.Engineering and would like to contribute, you can also write an article using or by posting an article contribute @ See my article appearing on the Python.Engineering homepage and help other geeks.

Please post comments if you find anything wrong or if you would like to share more information on the topic discussed above.

Get Solution for free from DataCamp guru