Python abs() Builtin Function
Python abs() function takes number as argument and returns the absolute value of given number.
In this tutorial, we will pass integer, floating point number or complex numbers as argument to abs() function, and observe the return value.
Syntax
The syntax to find the absolute value of a number is
result = abs(number)
The number could be integer, floating point number, complex number, or any object that implements __abs__() function.
Absolute Value of Integer
Pass an integer to abs() function, and it shall return its absolute value.
In the following example, we will call abs() function and pass a positive integer and negative integer to it.
Python Program
#positive integer
i = 14
result = abs(i)
print(f'abs({i}) is {result}')
#negative integer
i = -14
result = abs(i)
print(f'abs({i}) is {result}')
Output
abs(14) is 14
abs(-14) is 14
Absolute Value of Floating Point Number
Pass a floating point number to abs() function, and it shall return its absolute value.
In the following example, we will call abs() function and pass a float value and negative float value to it.
Python Program
#positive floating point number
f = 14.52
result = abs(f)
print(f'abs({f}) is {result}')
#negative floating point number
f = -14.52
result = abs(f)
print(f'abs({f}) is {result}')
Output
abs(14.52) is 14.52
abs(-14.52) is 14.52
Absolute Value of Complex Number
Pass a complex number to abs() function, and it shall return the magnitude of given complex number.
In the following example, we will call abs() function and pass complex number to it.
Python Program
#complex number with positive real and imaginary parts
c = 3 + 4j
result = abs(c)
print(f'abs({c}) is {result}')
#complex number with negative real and imaginary parts
c = -3-4j
result = abs(c)
print(f'abs({c}) is {result}')
Output
abs((3+4j)) is 5.0
abs((-3-4j)) is 5.0
Conclusion
In this Python Tutorial, we learned about abs() builtin function in Python, with the help of example programs.