5 different methods to use an else block in python

Written by sureshdsk | Published 2015/10/19
Tech Story Tags: programming | python | coding

TLDRvia the TL;DR App

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'

output

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 = 40is_pass = True if mark >= 50 else Falseprint "Pass? " + str(is_pass)

output

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 ielse:print 'For loop completed the execution'

output

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 iif i == 5:breakelse:print 'For loop completed the execution'

output

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 = 0loop = 0while a <= 10:print aloop += 1a += 1else:print "While loop execution completed"

output

a = 50loop = 0while a > 10:print aif loop == 5:breaka += 1loop += 1else:print "While loop execution completed"

output

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_nameelse:# Executes only if file opened properlyprint file_name, 'has', len(f.readlines()), 'lines'f.close()

output

Originally posted on http://www.idiotinside.com/2015/10/18/5-methods-to-use-else-block-in-python/


Written by sureshdsk | Software Architect | Pythonista 🔥
Published by HackerNoon on 2015/10/19