4 ‘Else Clauses’ in Python

Let’s learn about if-else, for-else, while-else, and try-else clauses in Python.

Photo by You X Ventures on Unsplash

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:

  1. if-else
  2. for-else
  3. while-else
  4. 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.

Photo by Author

Example 1: If-else clause

Executed the below code three times.

  1. First-time input is given as 7. If clause x>5 evaluated to True and only if suite is executed. No other part of the if statement is evaluated or executed.
  2. Second-time input is given as 5. If clause x>5 and elif clause x<5 is evaluated to False, so by default else suite is executed.
  3. Third-time input is given as 3.If clause x>5 is 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 else clause, if present, is executed, and the loop terminates.
Image by Author

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
Photo by Author

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<5 is 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 tryfinally statement, the finally clause is also executed ‘on the way out.’

Image by Author

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, and try block.
  • 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 break statement is executed in the while suite, it will terminate the loop without executing the else clause’s suite.

I hope you have found this article helpful — thanks for reading!

Resources(Python Documentation).

while-else clause

for-else clause

try-else clause

if-else clause

Exceptions

Compound statements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s