In Python, using an else conditional expression with a for loop

In Python, using an else conditional expression with a for loop

The use of else statements has been reduced in most programming languages (C/C++, Java, and so on) in favour of if conditional statements. With for loops, Python also allows us to employ the else condition.

When the loop is not terminated by a break statement, the else block shortly after for/while is run.

Else block is executed in below Python 3.x program: 

for i in range(1, 5):
    print(i)
else# Executed because no break in for
    print("No Break")



Output:
1
2
3
4
No Break
Else block is NOT executed in below Python 3.x program: 


for i in range(1, 4):
    print(i)
    break
else: # Not executed as there is a break
    print("No Break")


Output:

1
This type of else is only useful if there is an if condition
inside the loop that is dependent on the loop variable in some way The else statement will only be run in the following example if no element of the array is even, i.e. if the statement has not been executed for any iteration. As a result, the if statement is
run in the third iteration of the loop for the array [1, 9, 8], and the else statement after the for loop is disregarded. Because the if is not executed for any iteration in the array [1, 3, 5], the else is executed after the loop.
# Python 3.x program to check if an array consists
# of even number
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

As an exercise, predict the output of the following program.


count = 0
while (count < 1):   
    count = count+1
    print(count)
    break
else:
    print("No Break")


Post a Comment

0 Comments