Python abs() function
The abs()
function in Python returns the absolute value of a given number. The absolute value of a number is the non-negative value of the number, without regard to its sign. For example, the absolute value of -5
is 5
, and the absolute value of 5
is also 5
.
Syntax
- x: A number. This can be an integer, floating-point number, or a complex number.
Return Value
- If
x
is a positive number or0
, it returnsx
itself. - If
x
is a negative number, it returns the positive version ofx
. - If
x
is a complex number, it returns the magnitude (Euclidean distance from the origin).
Examples
Using
abs()
with integers:Using
abs()
with floating-point numbers:Using
abs()
with complex numbers: When used with a complex number,abs()
returns the magnitude (modulus) of the complex number, which is the distance of the complex number from the origin in the complex plane.For a complex number
a + bj
, the magnitude is calculated as:So, for
3 + 4j
, it returns5.0
because:
Summary
- The
abs()
function is used to find the absolute value of an integer or float, or the magnitude of a complex number. - It is useful in scenarios where only the magnitude of a value is important, not the sign.