fbpx

The function below sums up two numbers with Python:

def addition( a , b ): 
   return a + b 

print( addition( 4, 5 ) )
print( addition( 2, 2.5 ) )

The function will work with integers and floats. If however the function is run with an integer and a string, the following error is produced

print( addition( 4, "5" ) )
TypeError: unsupported operand type(s) for +: 'int' and 'str'

To overcome this limitation, you can wrap your function in a try-except block such as:

def addition( a, b ):
    try:
        return a + b
    except:
        print("Make sure your numbers are integers or floats and not strings")

and when we run this with a string, we get this instead:

print( addition( 4, "5" ) )
Make sure your numbers are integers or floats and not strings