abs() is a built-in function, so just replace all occurrences of math.abs with abs.
You should also use the isinstance() function for type checking instead of using type() and comparing, for example:
def distance_from_zero(num):
if isinstance(num, (int, float)):
return abs(num)
else:
return "Not an integer or float!"
Note that you may also want to include long and complex as valid numeric types.
Python math module doesn't have abs - Stack Overflow
Why Math.abs() doesn't work on values that are the MIN_VALUE of the data type?
Differences in abs()
Help with absolute value
Videos
abs() is a built-in function, so just replace all occurrences of math.abs with abs.
You should also use the isinstance() function for type checking instead of using type() and comparing, for example:
def distance_from_zero(num):
if isinstance(num, (int, float)):
return abs(num)
else:
return "Not an integer or float!"
Note that you may also want to include long and complex as valid numeric types.
As others pointed out, abs is builtin so it isn't imported from the math module.
I wanted to comment on your type checking. Another way that is the most "pythonic" is to use a try: except: block to check the type:
def distance_from_zero(num):
try:
return abs(num)
except ValueError:
return "Not an numeric type!"
This takes care of the issue that F.J. pointed out, that long and complex won't be considered. This example uses "duck typing" (if it walks like a duck and quacks like a duck, it must be a duck). If abs works, your function succeeds. If you supply something abs doesn't know how to handle a ValueError will be raised an it will return your error message.