How to use else statement with Loops in Python?



In this article, we will show you how to use else statements with loops in python.

Many of us are confused by the term else because else in an if-else condition makes sense, but an else for a loop? Weird! Python provides you with an additional feature with its loops.

Else with the loop is used with both the while and for loops. The else block is run at the end of the loop, which means that it is executed when the specified loop condition is false.

Syntax

for loop with optional else clause

for variable_name in iterable:
 #stmts in the loop
 .
 .
 .
else:
 #stmts in else clause
 .
 .

Syntax

for loop with optional else clause

while condition:
 #stmts in the loop
 .
 .
 .
else:
 #stmts in else clause
 .
 .

Using else statement with for loop in python

In other languages, the else functionality is only provided in if-else pairs. But Python allows us to implement the else functionality with for loops as well.

The else functionality is available for use only when the loop terminates normally. In case of forceful termination of the loop else statement is overlooked by the interpreter and hence its execution is skipped.

.

NOTE: When the loop is not terminated by a break statement, the else block immediately after for/while is executed.

Method 1: For-Else Construct with normal termination (without break statement)

Example

The following program shows how to use the else statement with for loop −

for i in ['T','P']: print(i) else: # Loop else statement # there is no break statement in for loop, hence else part gets executed directly print("ForLoop-else statement successfully executed")

Output

On executing, the above program will generate the following output −

T
P
ForLoop-else statement successfully executed

Method 2: For-Else Construct with forceful termination (with break statement)

Example

The following program shows how else conditions work in case of a break statement −

for i in ['T','P']: print(i) break else: # Loop else statement # terminated after 1st iteration due to break statement in for loop print("Loop-else statement successfully executed")

Output

On executing, the above program will generate the following output −

T

Explanation

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.

In Method 1, the loop else statement is executed since the for loop terminates normally after iterating over the list['T','P']. However, in Method 2, the loop-else statement is not executed since the loop is forcedly stopped using jump statements such as break.

These Methods clearly show that when the loop is forcedly terminated, the loop-else expression is not executed.

Now consider an example in which the loop-else statement is performed in some conditions but not in others.

Method 3: For-Else Construct with break statement and if conditions

Example

The following program shows how else conditions works in case of break statement and conditional statements −

# creating a function to check whether the list item is a positive # or a negative number def positive_or_negative(): # traversing in a list for i in [5,6,7]: # checking whether the list element is greater than 0 if i>=0: # printing positive number if it is greater than or equal to 0 print ("Positive number") else: # Else printing Negative number and breaking the loop print ("Negative number") break # Else statement of the for loop else: # Statement inside the else block print ("Loop-else Executed") # Calling the above-created function positive_or_negative()

Output

On executing, the above program will generate the following output −

Positive number
Positive number
Positive number
Loop-else Executed

Using else statement with while loop in python

Else-While without break statement

Algorithm (Steps)

Following are the Algorithm/steps to be followed to perform the desired task −

  • Initialized k value with 0.

  • Using a while loop to traverse until the specified condition is true(until k<8).

  • Incrementing the k value by 1, since we don't want to execute the while loop infinite times.

  • Print k value.

  • Else block gets executed when the condition fails/becomes false i.e when the k value becomes 8.

Example

The following program demonstrates the use of the else statement in the while loop −

k=0 # traversing until the condition is true(k<8) while k<8: # incrementing the k value by 1 k+=1 # printing k value print("k =",k) else: # else block gets executed when the condition fails(becomes false) print("This is an else block")

Output

On executing, the above program will generate the following output −

k = 1
k = 2
k = 3
k = 4
k = 5
k = 6
k = 7
k = 8
This is an else block

Using Else statement in While loop with a break statement

Example

The following program shows how else conditions work in case of break statements of while loop −

# creating a function that checks if the # list passed to it contains an even number def hasEvenNumber(l): # getting the list length n = len(l) # intializing a variable with 0(index) i = 0 # traversing the loop until the I value is less than the list length while i < n: # checking whether the corresponding index element of a list is even if l[i] % 2 == 0: # printing some text, if the condition is true print("The input list contains an even number") # giving a break statement/break the loop break # incrementing the I (index) value by 1 i += 1 else: # Else print "The input list doesn't contain an even number" # It executes Only if the break is NEVER met and the loop is terminated after all iterations print("The input list doesn't contain an even number") # calling the hasEvenNumber() function by passing input list 1 as an argument print("For Input list 1:") hasEvenNumber([3, 9, 4, 5]) # calling the hasEvenNumber() function by passing input list 2 as an argument print("For Input list 2:") hasEvenNumber([7, 3, 5, 1])

Output

On executing, the above program will generate the following output −

For Input list 1:
The input list contains an even number
For Input list 2:
The input list doesn't contain an even number

Conclusion

This article taught us how to use Python's else statements in for and while loops. Additionally, we learned how the break statement behaves in the event of an else statement.


Advertisements