Python abs() Function
The abs() function available in Python standard library determines the absolute value of a specified numeric number, which is the (positive) distance between x and zero.
This function works on integer, floats, and complex numbers. In the case of complex number, abs() function only returns the magnitude part.
Syntax:
The general syntax to define abs() function is as:
abs(x)
Parameter:
This function takes a parameter x that may be an integer, a floating point number, or an object implementing __abs__(). If the parameter x is a complex number, the function returns its magnitude.
Return type:
The abs() function returns the absolute value of a number as integer, floating-point, and the magnitude of a complex number, depending upon the value.
abs() Function Example Programs
Let’s take some example programs based on the use of abs() function in Python.
Example 1:
# Program to demonstrate the use of abs() function.
print("Absolute value of -20 is: ",abs(-20))
print("Absolute value of +20 is: ", abs(+20))
print("Absolute value of -20.33 is: ", abs(-20.33))
print("Absolute value of 2 - 4j is: ", abs(2 - 4j))
Output: Absolute value of -20 is: 20 Absolute value of +20 is: 20 Absolute value of -20.33 is: 20.33 Absolute value of 2 - 4j is: 4.47213595499958
Example 2:
# Program to getting an absolute value of binary, octal and hexadecimal numbers.
# Using of abs() function.
num1 = -0b10011
num2 = -0o10
num3 = -0x40
print("Absolute value of -0b10011 is:", abs(num1))
print("Absolute value of -0o10 is:", abs(num2))
print("Absolute value of -0x40 is:", abs(num3))
Output: Absolute value of -0b10011 is: 19 Absolute value of -0o10 is: 8 Absolute value of -0x40 is: 64
In this tutorial, you have learned about Python built-in abs() function with the help of example programs. Hope that you will have understood the basic points of abs() function.
Thanks for reading!!!