Python abs() built-in function
From the Python 3 documentation
Return the absolute value of a number. The argument may be an integer, a floating point number, or an object implementing __abs__()
. If the argument is a complex number, its magnitude is returned.
Introduction
The abs()
function in Python is a built-in function that returns the absolute value of a number. It can handle integers, floating-point numbers, and even complex numbers (returning their magnitude). This function is useful when you need to ensure a value is positive, regardless of its original sign.
Examples
# For integers
>>> abs(-1)
# 1
>>> abs(0)
# 0
# For floats
>>> abs(-3.14)
# 3.14
# For complex numbers (returns magnitude)
>>> abs(3 + 4j)
# 5.0
# For other number systems
>>> abs(0x10) # Hexadecimal
# 16
>>> abs(0b10) # Binary
# 2
>>> abs(0o20) # Octal
# 16