In this HowTo i’ll explain how the Python absolute function works.
What is the Python absolute value function?
The Python absolute value function removes the minus sign from a number (it’s positive number).
abs(-10) # Returns 10
abs(-3) # Returns 3
The values you give to the abs() function can be a sum or a variable, you’ll still get a positive number returned without the minus sign.
abs(24 - 50) # 26
negativeNumber = -43
abs(negativeNumber) # 43
Of course, as with other Python functions in order to save the value that is returned by the abs() function the result of the function needs to be assigned to a variable.
negativeNumber = -99
positiveNumber = abs(negativeNumber)
The numbers you pass to the abs() function can be an integer or a float. If you try and use a string, you will get a TypeError exception. The function takes exactly 1 argument only. It is a built in function so can be used in Python programs without importing anything. It will work in either Python version 2.x or 3.x
When might you use the Python absolute function?
The Python absolute function might be useful if you are trying to calculate the numerical difference between two negative numbers. A classic example of this is when you are working with coordinates and there is a central point which is noted by a 0.