Python provides the
abs() as a built-in method to calculate the absolute value of a number. The number can be an integer, floating-point, etc. The absolute value is providing the positive value of the specified number event it is a negative number.
abs() Method Syntax
The abs() method has the following syntax. The abs() method returns the same type like if the NUMBER is integer returned value is an integer, floating-point returns floating-point, complex number returns complex number.
- NUMBER can be an integer, floatin-point or complex number.
Absolute Value of Integer
One of the most popular usages of the abs() method is returning the positive or absolute value of the provided integer.
a = -5 b = 5 absolute_integer = abs(a) print(absolute_integer) absolute_integer = abs(b) print(absolute_integer) absolute_integer = abs(-5) print(absolute_integer)
5 5 5
Absolute Value of Floating Point
Floating-point numbers can be negative or positive. So the abs() method can be used to get the absolute value of a floating-point number as a value or variable. The returned absolute number type is also a floating point too.
a = -5.5 b = 5.5 absolute_floating_point = abs(a) print(absolute_floating_point) absolute_floating_point = abs(b) print(absolute_floatin_point) absolute_floating_point = abs(-5.5) print(absolute_floating_point)
5.5 5.5 5.5
Absolute Value of Complex Number
Even it is not so popular the absolute value of the complex number can be calculated with the abs() method. The returned type for the complex number is a complex number too.
c = (3-4j) absolute_complex = abs(c) print(absolute_complex)