I have for instance this function I wrote and want to assure that the argument is a number when I call the function.

def hypotenuse(n):
    "return the length of the hypotenuse of an isosceles triangle"
    return (n*n + n*n)**0.5
 
sides = 3.7
print hypotenuse(sides)

Any ideas how to do this?

Recommended Answers

All 3 Replies

I have for instance this function I wrote and want to assure that the argument is a number when I call the function.

def hypotenuse(n):
    "return the length of the hypotenuse of an isosceles triangle"
    return (n*n + n*n)**0.5
 
sides = 3.7
print hypotenuse(sides)

Any ideas how to do this?

>>> def hyp(n):
...     if isinstance(n, (float, int)):
...         return (2*(n*n))**0.5
...     else:
...         raise ValueError, 'Invalid argument'
...     
>>> hyp(3)
4.2426406871192848
>>> hyp(7.5)
10.606601717798213
>>> hyp('t')
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 5, in hyp
ValueError: Invalid argument
>>>

If you don't want to change your original function you can attach a decorator just above the function as shown ...

# intercept a wrong data type with a function decorator
 
def require_num(func):
    """decorator to check if a function argument is a number"""
    def wrapper (arg):
        if type(arg) in (int, float):
            return func(arg)
        else:
            print "Error: need numeric value!"
    return wrapper
 
@require_num
def hypotenuse(n):
    "return the length of the hypotenuse of an isosceles triangle"
    return (n*n + n*n)**0.5
 
print hypotenuse(3.7)  # 5.23259018078
print hypotenuse(3)    # 4.24264068712
print hypotenuse('a')  # Error: need numeric value!

Might be a little advanced for a beginner, but then it is just one of the many advanced features Python has up its sleaves.

Then there's try ... except:

def hypotenuse(n):
    "return the length of the hypotenuse of an isosceles triangle"
    try:
        return (n*n + n*n)**0.5
    except:
        return 'Invalid'
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.