mercredi 26 août 2020

Which Python Code is better for the same solution? If.. Else statements

I am learning pythong at the moment and I have written a quite simple code. But the solution provided is different. Both codes are giving me the same result. I just want to understand which code is better or more efficient and why?

Thank you

## Write a Python program to add two objects if both objects are an integer type

def itg (x,y):
    sum = x + y
    if type(x) is int and type(y) is int:
        return sum
    else:
        return "The values must be intergers"

print (itg(4.22,4))


## Other way:

def add_numbers(a, b):
    if not (isinstance(a, int) and isinstance(b, int)):
         raise TypeError("Inputs must be integers")
    return a + b

print(add_numbers(10, 20))

Aucun commentaire:

Enregistrer un commentaire