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.
Consider the below example.
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
Consider the below example.
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
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
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.
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
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.