5 different methods to use an else block in python

来源:互联网 时间:1970-01-01

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.

if-else.py x = Trueif 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.

if-else-short.py

mark = 40is_pass = True if mark >= 50 else Falseprint "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-else-2.py for i in range(10): print ielse: 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-else.py for i in range(10): print i if i == 5: breakelse: 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.

while-else.py a = 0loop = 0while a <= 10: print a loop += 1 a += 1else: print "While loop execution completed"

while-else.py a = 50loop = 0while a > 10:print aif loop == 5:breaka += 1loop += 1else: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.

try-except-else.py

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()

Based on Quora answers: https://www.quora.com/When-can-you-use-an-else-block-in-Python

相关阅读:
Top