The abs() function in Python is a built-in function that returns the absolute value of a number. It can be used with both integers and floating-point numbers, and it always returns a positive value.
Parameter Values
| Parameter | Description |
|---|---|
| x | A numeric value or object for which the absolute value is computed. |
Return Values
The abs() function can return an int, float, or complex number.
How to Use abs() in Python
Example 1:
Return the absolute value of a number. The argument may be an integer or a floating-point number.
abs(-10) # Output: 10
Example 2:
The abs() function can also be used with complex numbers to return their magnitude.
abs(3+4j) # Output: 5.0
Example 3:
If a custom class defines the __abs__() method, abs() can be called on objects of the class.
class CustomClass:
def __abs__(self):
return 100
obj = CustomClass()
abs(obj) # Output: 100