Python abs() Function With Syntax & Examples
The built-in library function abs()
in Python returns the absolute value of a given number (number in argument).
The number in argument (given number) can be of type integer, floating point number or complex number. Function abs() returns magnitude if the given number in argument is complex number.
abs() Syntax
The syntax of abs()
function is:
abs(number)
abs() Examples
Few examples for Python abs()
function are:
# absolute value of integer
>>> abs(-23)
23
# absolute value of floating point number
>>> abs(-34.56)
34.56
# absolute value of complex number
>>> abs(2+4j)
4.47213595499958
abs() Parameters
The abs()
function takes only one argument. which is:
- number - Number can be of type integer, floating point or complex number.
abs() Return Value
The abs(number)
function returns:
- When
number
is integer, it returns absolute integer number. - When
number
is float, it returns absolute floating point number. - When
number
is complex, it returns magnitude of complex number. - When
number
defines__abs()__
, thenabs(number)
returnsnumber.__abs__()
.
Programs Using abs()
Example 1: Finding absolute value of an integer number
Following Python program calculates absolute value of an integer number given by user. Number is read using input()
function and stored in variable number
.
Program
# absolute value of an integer
number = int(input("Enter any number: "))
print("Absolute value of given number is:", abs(number))
Output
Enter any number: -34 Absolute value of given number is: 34
Example 2: Finding absolute value of float
number
Following Python program calculates absolute value of floating point number given by user. Floating point numbers are those numbers that contain floating decimal points.
Program
# absolute value of an floating point number
number = float(input("Enter any number: "))
print("Absolute value of given number is:", abs(number))
Output
Enter any number: -45.678 Absolute value of given number is: 45.678
Example 3: Finding magnitude of complex number
Following Python program calculates magnitude of complex number set in variable complex_number
.
Program
complex_number = 5-4j
print('Magnitude of complex number = ', abs(complex_number))
Output
Magnitude of complex number = 6.4031242374328485
Example 4: Implementing __abs__()
for custom class
We can change the behavior of abs()
by implementing method __abs__()
for the class we are working with. See example below:
Program
class Custom:
def __abs__(self):
return 'hello'
a = Custom()
print(abs(a))
Output
hello