1

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

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.