In most programming languages like C, C++, Java and more, the use of else statements restricts with the if conditional statements. However, in Python, it is allowed to make use of the else condition with for loops. In other words, the else block just after for/while executes only when the loop does not terminate by a break statement. You will see how else block executes below in Python 3.x program:
for i in range(1, 4):
print(i)
else: # Executed because no break-in for
print("No Break")
Output:
1
2
3
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
Meaning to say, this kind of else is beneficial only if there is an if condition present inside the loop which is in some way dependent on the loop variable.
In the example given below, you will see that the else statement only executes if no element of the array is even. Meaning to say, if the statement does not execute for any iteration. Thus, for the array [1, 9, 8], the if executes in the third iteration of the loop.
Therefore, the else present after the for loop gets ignored. In case of array [1, 3, 5] the if does not execute for any iteration and thus the else after loop gets executed.
# Python 3.x program for checking 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
Browse more Topics Under Conditional Constructs and Looping
- If Else Statement While
- For (Range Function)
- Break
- Continue
- Pass
- Nested if
- Nested Loops
- Use of Compound Expression in Conditional and Looping Construct
Else Clauses on Loop Statements
In Python, the loop statements have a feature that many users like and some disliked. It is also something many have not encountered or find confusing, it is an else clause. In order to understand the reason for this frequent confusion, you need to study in detail all about this clause.
Why is it Confusing?
The main reason many developers feel the behaviour of these clauses is confusing is evident in the example below:
>>> if [1]:
... print("Then")
... else:
... print("Else")
...
Then
>>> for x in [1]:
... print("Then")
... else:
... print("Else")
...
Then
Else
You will notice that the if <iterable> header appears to be very similar to the <var> in <iterable> header. Therefore, it is very natural to assume that they are related and expect the clause to be skipped in both cases.
Moreover, as the example displays, the assumption is incorrect. In the second case, the else clauses triggers even though the iterable is not empty.
If you take a look at a common while loop pattern instead, it will just add to the confusion as it seems to line up with the way one would expect the conditional to work:
>>> x = [1]
>>> while x:
... print("Then")
... x.pop()
... else:
... print("Else")
...
Then
Else
>>> if x:
... print("Then")
... else:
... print("Else")
...
Else
Over here, the loop runs until the iterable is empty. Then the else clause executes, just as it is in the if statement.
A Different Type of Else
What is happening then? The reality is that the superficial similarity between if <iterable> and for <var> in <iterable> is relatively deceiving. If you call the else clause on an if statement a “conditional else”, then you can look to try statements for a different type of else clause, a “completion clause”:
>>> try:
... pass
... except:
... print("Then") # The try block threw an exception
... else:
... print("Else") # The try block didn't throw an exception
...
Else
Most importantly, with a completion clause, the question that is being asked has to do with how an earlier suite of code finished, instead of checking the boolean value of an expression. Thus, reaching the else clause in a try statement will mean that the try block actually completed successfully. Meaning to say, it did not throw an exception or otherwise terminate before reaching the end of the suite.
You see how this is a much better model for what is happening in our for a loop as the condition the else is checking for is whether or not the loop explicitly terminated by a break statement.
Although it is not legal syntax, it can be useful to mentally insert an except break: pass whenever you encounter a loop with an associated else clause in order to help remember what it means:
for x in iterable:
...
except break:
pass # Implied by Python's loop semantics
else:
... # No break statement was encountered
while condition:
...
except break:
pass # Implied by Python's loop semantics
else:
... # No break statement was encountered
FAQ on Else
Question 1: What is the difference between conditional constructs and loops?
Answer 1: Conditional statements check whether a condition is true or false. On the other hand, a loop refers to a structure that executes repeatedly depending upon the value of the conditional statements. Further, the conditional statement will execute only once if the condition is true while a loop will be executed repeatedly till the condition turns false.
Question 2: What is for else in Python?
Answer 2: Python allows the users to use the else condition with for loops. Further, the else block just after for/while executes only when the loop does not terminate by a break statement. This type of else comes into use only if there is an if condition present inside the loop which somehow is dependent on the loop variable.
Question 3: What is the while loop in Python?
Answer 3: In Python, the while loop comes into use over a block of code as long as the test expression (condition) is true. Moreover, this loop usually comes into use when one does not know the number of times to iterate beforehand.
Leave a Reply