Python math module doesn't have abs - Stack Overflow
Calculating absolute value in Python - Stack Overflow
Absolute value without calling the Math.abs() method?
I think you can probably figure this one out just with a hint.
What happens to negative numbers when they are multiplied by -1?
Note that you can check if numbers are less than zero using if and then do something about less than zero numbers.
If you still get stuck after thinking on that for a few minutes shoot me a pm.
Edit: as long as you don't ask me to just write out all the code for you.
More on reddit.comHelp 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.
You can do it with the built-in abs() function:
absolute_val = abs(x)
Otherwise, without the built-in function, use math:
absolute_val = (x ** 2) ** 0.5
You wanted to calculate the absolute value using python. Here Im providing the code:
Python code function: abs(Number)
Python code example: abs(-100)
Python code example: abs(105-20)
Python code example: abs(100-200)
Output:
