5 different ways to use an else block in python

There are several ways to use an else block in python. Lets look at each method and its usecase.

1. if else

This is commonly used if else block. if block is executed if the condition is true otherwise else block will be executed.


x = True

if x:
    print 'x is true'
else:
    print 'x is not true'

2. if else shorthand

This if else shorthand method is a ternary operator equivalent in pythom if else statement. If you loot at the code, boolean value True will assigned to the variable is_pass if the expression mark >= 50 is true, otherwise False will be assigned.


mark = 40
is_pass = True if mark >= 50 else False
print "Pass? " + str(is_pass)

3. for-else loop

We can use an else block on a for loop too. The else block is executed only when the for loop completes its iteration without breaking out of the loop.

for loop below, will print from 0 to 10 and then 'For loop completed the execution' as it doesn't break out of the for loop.


for i in range(10):
    print i
else:
    print 'For loop completed the execution'

for loop below, will print from 0 to 5 and then breaks out of the for loop, so else block will not be executed.

for i in range(10):
    print i
    if i == 5:
        break
else:
    print 'For loop completed the execution'

4. while-else loop

We can also use an else block with while loop, The else block is executed only when the while loop completes its execution without breaking out of the loop.

a = 0
loop = 0
while a <= 10:
    print a
    loop += 1
    a += 1
else:
    print "While loop execution completed"
a = 50
loop = 0
while a > 10:
    print a
    if loop == 5:
        break
    a += 1
    loop += 1
else:
    print "While loop execution completed"

5. else on try-except

We can use an else block on a try except block too. This is type of not required in most cases. The else block is only executed if the try block doesn't throw any exeception.

In this code, else block will be executed if the file open operation doesn't throw i/o exception.

file_name = "result.txt"
try:
    f = open(file_name, 'r')
except IOError:
    print 'cannot open', file_name
else:
    # Executes only if file opened properly
    print file_name, 'has', len(f.readlines()), 'lines'
    f.close()

I am currently doing #100DaysOfCode challenge, follow me on twitter to know what I do everyday.

Did you find this article valuable?

Support Suresh Kumar by becoming a sponsor. Any amount is appreciated!