Latest news about Bitcoin and all cryptocurrencies. Your daily crypto news habit.
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 = 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.
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 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 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.
a = 0loop = 0while a <= 10: print a loop += 1 a += 1else: print "While loop execution completed"
a = 50loop = 0while a > 10: print a if loop == 5: break a += 1 loop += 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.
file_name = "result.txt"try: f = open(file_name, 'r')except IOError: print 'cannot open', file_nameelse: # Executes only if file opened properly print file_name, 'has', len(f.readlines()), 'lines' f.close()
Originally posted on http://www.idiotinside.com/2015/10/18/5-methods-to-use-else-block-in-python/
5 different methods to use an else block in python was originally published in Hacker Noon on Medium, where people are continuing the conversation by highlighting and responding to this story.
Disclaimer
The views and opinions expressed in this article are solely those of the authors and do not reflect the views of Bitcoin Insider. Every investment and trading move involves risk - this is especially true for cryptocurrencies given their volatility. We strongly advise our readers to conduct their own research when making a decision.