Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 21, 2022 07:05 am GMT

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

follow me on twitter to get more content and connect with me.


Original Link: https://dev.to/kcdchennai/5-different-ways-to-use-an-else-block-in-python-47j0

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To