Reza Rahnama
Reza Rahnama

Reputation: 11

except ValueError in Python

Is there better way of writing this code:

def add (exe1, exe2):
    try:
        a = float (exe1)
        b = float (exe2)
        total = float (a + b)
    except ValueError:
        return None
    else:
        return total

Upvotes: 1

Views: 1049

Answers (2)

YiFei
YiFei

Reputation: 1834

You can also use contextlib.suppress, if you find it more readable.

from contextlib import suppress
def add(exe1, exe2):
    with suppress(ValueError):
        return float(exe1) + float(exe2)

See the documentation here.

Upvotes: 0

randomir
randomir

Reputation: 18697

You can have it all inside a try/except block (calculation and return):

def add(exe1, exe2):
    try:
        return float(exe1) + float(exe2)
    except ValueError:
        return None

Also note, the default return value from function is None, so the second return is not really necessary (you could have pass instead), but it makes code more readable.

Upvotes: 1

Related Questions