Built-in Functions
abs()
Returns the absolute (non-negative) value of a number or magnitude of a complex number.
abs(num)
The abs() function returns the absolute value of a given number. If the argument is a complex number, it returns its magnitude (Euclidean distance from the origin).
In mathematics, the absolute value of a real number is its non-negative value regardless of its sign. For example, abs(-15) is 15, and abs(15) is 15.
Parameters
| Name | Description |
|---|---|
| num | A numeric value. Can be an int, float, complex number, or any custom object that implements the __abs__() special method. |
Returns
Returns the absolute value of num:
- For integers and floats, returns the non-negative value as the same type.
- For complex numbers
a + bj, returns its magnitudesqrt(a² + b²)as a float.
Try it
Run it and change it
# Absolute value of integers and floating-point numbers
int_num = -25
float_num = -55.85
print('abs(-25) =', abs(int_num))
print('abs(-55.85) =', abs(float_num))
print('abs(100) =', abs(100))
Another example
# Absolute value of a complex number and custom objects
complex_num = 3 - 4j
print('Magnitude of 3 - 4j =', abs(complex_num))
# Custom class defining __abs__
class Vector2D:
def __init__(self, x, y):
self.x = x
self.y = y
def __abs__(self):
return (self.x**2 + self.y**2) ** 0.5
vec = Vector2D(6, 8)
print('Vector length =', abs(vec))
Worth knowing
- TypeError: Passing a non-numeric type like a string or list (e.g.
abs("hello")) raises aTypeError: bad operand type for abs(). - Complex Numbers: For a complex number
z = x + yj,abs(z)calculatesmath.hypot(z.real, z.imag). - Custom Dunder Method: Custom classes can define their own absolute value behavior by implementing the
__abs__(self)method.