Let’s learn about if-else, for-else, while-else, and try-else clauses in Python.
Else-Clauses in Python
In Python, we might find else clause in if statement, for, while loops, and try block also. else clause is optional in all these statements. Let’s see how else block is executed in all these statements and loops.
4 else clauses in python:
- if-else
- for-else
- while-else
- try-else
Compound Statements
Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way.
if,while,for, try are compound statements.
The if, while and for statements implement traditional control flow constructs.
try specifies exception handlers and/or cleanup code for a group of statements.
- A compound statement consists of one or more ‘clauses.’
- A clause consists of a header and a ‘suite.’
- The clause headers of a particular compound statement are all at the same indentation level.
- Each clause header begins with a uniquely identifying keyword and ends with a colon.
- A suite is a group of statements controlled by a clause.
Syntax for-else clause:
for item in iterable: --->header
suite
else:
suite
If-Else Clause:
The if statement is used for conditional execution.
Syntax if-else clause:
if assignment_expression:
suite
elif assignment_expression:
suite
else:
suite
If statement will select exactly one of the suites by evaluating the expressions one by one until one is found to be true, then that suite is executed (and no other part of the if statement is executed or evaluated).
If all expressions are false, the suite of the else clause, if present, is executed.
Only one suite will be executed in the if statement.[either if-suite or elif-suite or else-suite).
There can be zero or more elif clause, and the else clause is optional.
Example 1: If-else clause
Executed the below code three times.
- First-time input is given as
7. If clausex>5evaluated to True and only if suite is executed. No other part of the if statement is evaluated or executed. - Second-time input is given as
5.If clausex>5and elif clausex<5is evaluated to False, so by default else suite is executed. - Third-time input is given as
3.If clausex>5is evaluated to False. Then elif clause evaluated returns True, so elif suite is executed. Else clause is not executed.
x = int(input("Please enter an integer: "))
if x>5:
print ("Greater than 5")
elif x<5:
print ("Less than 5")
else:
print ("The number is 5")
print ("Outside if-else block")
'''
Output 1 :
Please enter an integer: 7
Greater than 5
Outside if-else block
Output 2:
Please enter an integer: 5
The number is 5
Outside if-else block
Output 3:
Please enter an integer: 3
Less than 5
Outside if-else block
'''
for-else clause
The for statement is used to iterate over the elements of a sequence (such as a string, tuple, or list) or other iterable objects.
for loop may have an else clause; it is executed when the for loop terminates through exhaustion of the iterable.
But not when the loop is terminated by a break statement.
Syntax:
for item in iterable:
suite
else:
suite
- The iterable is evaluated only once. An iterator is created for the result of that iterable.
- The suite is then executed once for each item provided by the iterator, in the order returned by the iterator.
- When the items are exhausted, the suite in the
elseclause, if present, is executed, and the loop terminates.
Example :for-else clause
- else clause is executed when the for loop terminates after the exhaustion of the iterable.
for i in [1,2,3,4,5]:
print (i)
else:
print ("for loop is done")
print ("Outside the for loop")
'''
1
2
3
4
5
for loop is done
Outside the for loop
'''
While-else clause
The while statement is used for repeated execution as long as an expression is true.
while expression:
suite
else:
suite
This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the else clause, if present, is executed and the loop terminates.
Example 9: Using else clause in a while loop.
- while loop is executed until the condition
i<5is False. - else clause is executed after the condition is False.
i=0
while i<5:
print (i)
i+=1
else:
print ("Element is greater than 5")
''' Output: 0 1 2 3 4 Element is greater than 5 '''
Refer to my story break,continue statements in for,while loop
try-else clause
The try statement specifies exception handlers and/or cleanup code for a group of statements:
Syntax:
try:
suite
except Exception:
suite
else:
suite
finally:
suite
try:
In the try block, code is executed and if an exception is raised, control goes to the except clause. If no exception is raised, no exception handler is executed.
except:
The except clause(s) specify one or more exception handlers.
This block is executed only if an exception is raised in the try block.
else:else clause is executed if the control flow leaves the try suite, no exception was raised, and no return, continue, or break statement was executed.
finally:finally specifies a ‘cleanup’ handler.
This block is always executed even if there is an exception raised in the try block or not.
Even when a return, break or continue statement is executed in the try suite of a try…finally statement, the finally clause is also executed ‘on the way out.’
Example 1: Exception is not raised in the try block.
try, else, and finally block are executed.
def add(a,b):
try:
result=a+b
except Exception as e:
print (e)
else:
print (result)
finally:
print ("Executed finally")
add(4,5)
'''
Output:
9
Executed finally
'''
Example 2: Exception is raised by try block.
try, except and finally blocks are executed
def add(a,b):
try:
result=a+b
except Exception as e:
print (e)
else:
print (result)
finally:
print ("Executed finally")
add({'a':1},{'b':2})
'''
Output:
unsupported operand type(s) for +: 'dict' and 'dict'
Executed finally
'''
Conclusion:
- else clause is optional in
if,for,while, andtryblock. - Only one suite will be executed in the if statement.[either if-suite or elif-suite or else-suite).
- else clause is executed if there is no exception raised in the try block
- else clause in for loop is executed when the for loop terminates through exhaustion of the iterable and not being terminated by a break statement.
- In the while loop, the else clause is executed after the condition is False. if
breakstatement is executed in thewhilesuite, it will terminate the loop without executing theelseclause’s suite.
I hope you have found this article helpful — thanks for reading!
Resources(Python Documentation).
Make a one-time donation
Make a monthly donation
Make a yearly donation
Choose an amount
Or enter a custom amount
Your contribution is appreciated.
Your contribution is appreciated.
Your contribution is appreciated.
Buy Me a CoffeeBuy Me a CoffeeBuy Me a Coffee