Answered # Assure n is a number

bvdet 75 vegaseat 1,720 jrcagle 77 Write a C program that should create a 10 element array of random integers (0 to 9). The program should total all of the numbers in the odd positions of the array and compare them with the total of the numbers in the even positions of the array and indicate ...

0

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
>>>
```

0

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.

0

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'
```

This question has already been answered. Start a new discussion instead.

Recommended Articles

Hi. so this is actually a continuation from another question of mineHere but i was advised to start a new thread as the original question was already answered.

This is the result of previous question answered :

code for the listbox - datagridview interaction

At the top of the code ...

the function that I created to find the ...