Else with loop is used with both while and for loop. The else block is executed at the end of loop means when the given loop condition is false then the else block is executed. So let’s see the example of while loop and for loop with else below.
Else with While loop
Consider the below example.
Python3
i = 0 while i< 5 : i + = 1 print ( "i =" ,i) else : print ( "else block is executed" ) |
Output:
i = 1 i = 2 i = 3 i = 4 i = 5 else block is executed
Explanation
- declare i=0
- we know then while loop is active until the given condition is true. and we check i<5 it’s true till the value of i is 4.
- i+=1 increment of i because we don’t want to execute the while loop infinite times.
- print the value of i
- else block execute when the value of i is 5.
Else with For loop
Consider the below example.
Python3
l = [ 1 , 2 , 3 , 4 , 5 ] for a in l: print (a) else : print ( "else block is executed" ) |
Output:
1 2 3 4 5 else block is executed
Explanation
- declare a list l=[1,2,3,4,5]
- for loop print a.
- else block is execute when the for loop is read last element of list.
Else with the break statement
The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
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. Therefore for the array [1, 9, 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.
Example 1: Using while loop
Python3
def contains_even_number(l): n = len (l) i = 0 while i < n: if l[i] % 2 = = 0 : print ( "list contains an even number" ) break i + = 1 # This else executes only if break is NEVER # reached and loop terminated after all # iterations else : print ( "list does not contain an even number" ) # Driver code print ( "For List 1:" ) contains_even_number([ 1 , 9 , 8 ]) print ( " \nFor List 2:" ) contains_even_number([ 1 , 3 , 5 ]) |
Output:
For List 1: list contains an even number For List 2: list does not contain an even number
Example 2: Using for loop
We will use the same example as above but this time we will use for loop instead of while loop.
Python3
def contains_even_number(l): for ele in l: if ele % 2 = = 0 : print ( "list contains an even number" ) break # This else executes only if break is NEVER # reached and loop terminated after all # iterations. else : print ( "list does not contain an even number" ) # Driver code print ( "For List 1:" ) contains_even_number([ 1 , 9 , 8 ]) print ( " \nFor List 2:" ) contains_even_number([ 1 , 3 , 5 ]) |
Output:
For List 1: list contains an even number For List 2: list does not contain an even number