user13740007
user13740007

Reputation:

What is the role of else in try-except-else coupling in python?

So basically, else block for if-else coupling only work when if condition is not met so it is kind of necessary. In for-else coupling and while-else coupling, its executed when the loop cannot be executed for some reason. So, what we can not accomplished by not using else in try-except-else coupling. I meant if the reason is to detect if no exception is raised, we can simply put a print statement in the end of try block to achieve it. What is the vital role of else in try-except-else coupling? (Hi all! I’m very new to programming and StackOverflow too. But I’ve tried to make the question as synced with decorum of site as possible)

Upvotes: 3

Views: 399

Answers (4)

jupiterbjy
jupiterbjy

Reputation: 3503

'else' runs when for, while loop finished without being interrupted.

To qoute Luciano Ramalho from his book 'Fluent Python',:

I think else is a very poor choice for the keywords in all cases except if. It implies an excluding alternative, like "Run this loop, otherwise to that," but the semantics for else in loops is the opposite: "Run this loop, then do that." This suggests then as a better keyword - which would also make sens in the try context: "Try this, then do that."

Done of nitpicking, why we use try-except-else then? EAFP style coding - at least I believe so.

EAFP - Easier ask Forgiveness Than Permission. Try something first, if error, then do else. This clearly shows coder's intention to catch cases.

This also results better performance if there's few things to trigger error. For example, let's see this extreme case:

import timeit
import random

source = [i for i in range(600000)]
source[random.randint(0, len(source))] = 'bam!'

def EAFP():
    numbers = []
    for n in source:
        try:
            result = n + 3
        except TypeError:
            pass
        else:
            numbers.append(result)


def LBYL():
    numbers = []
    for n in source:
        if isinstance(n, int):
            result = n + 3
            numbers.append(result)


print(f"{timeit.timeit(EAFP, number=10):.3f}")
print(f"{timeit.timeit(LBYL, number=10):.3f}")

Results(sec):

2.824
3.393

This would build up if there's more if statements to filter out more possible errors.

And, on readability aspect, lets quote 'Zen of python':

Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.

Multiple nested if is complex than flat try - except - except... - else chain.

Upvotes: 0

Paul Draper
Paul Draper

Reputation: 83273

So, what we can not accomplished by not using else in try-except-else coupling.

Consider

try:
    a()
except Exception:
    b()
else:
    c()

A.

try:
    a()
    c()
except Exception:
    b()

but that would catch and run b() if c() raises Exception. I believe this is probably what you are thinking of.

B.

try:
    a()
except Exception:
    b()
c()

but that could run c() when a() raises Exception.

C.

success = False
try:
    a()
    success = True
except Exception:
    b()
if success:
    c()

That is functionally equivalent, but more verbose and less clear. (And we haven't even included a finally block.)


try-except-else-finally is quite helpful for controlling the scope of caught errors.

Upvotes: 3

Prathamesh
Prathamesh

Reputation: 1057

If there is no error found in try block the else block is also executed, but when a error is cached only except block will be executed.

So, if you have a method that could, for example, throw an IOError, and you want to catch exceptions it raises, but there's something else you want to do if the first operation that is code in try block succeeds , and you don't want to catch an IOError from that operation,then in such situation the else block will be used.

try:
    statements # statements that can raise exceptions
except:
    statements # statements that will be executed to handle exceptions
else:
    statements # statements that will be executed if there is no exception

consider this example:

try:
    age=int(input('Enter your age: '))
except:
    print ('You have entered an invalid value.')
else:
    if age <= 21:
        print('You are not allowed to enter, you are too young.')
    else:
        print('Welcome, you are old enough.')

although there is no proper significance of using else ,because each time when there is no exception we can do our task in try block also.

hope this helps!

Upvotes: 0

Hamza
Hamza

Reputation: 6025

There is no such thing as coupling in python for else. All the constructs you mentioned above coupled with else will work just fine without even using else. You can use if, for, while and try-except all without else. However, the role of else in python is: to execute a code instead of the code in block just above.

Note that it is irrelevant to else that what block is above it or with whom it is coupled. It will only be executed if the block above is not. And resultant block maybe or may not be vital or something which cannot be achieved by other means.

Upvotes: 0

Related Questions