How to find the absolute value of a number with the Python abs() function
In this tutorial, you will learn how to find the absolute value of a given number using the Python abs() function, which takes one argument and returns the absolute value.
Python abs() Function Syntax
The syntax of the abs() function is as follows:
abs(number)
or:
number.__abs__(self)
Argument
- Number: It can be an integer or a floating point number.
Remark
- If the argument is a complex number, abs() returns its magnitude.
abs() Examples
Example 1: Absolute value of an integer
The following program returns an absolute value of -20:
#find the absolute value of an integer number (-20): abs_value = abs(-20) print ("The absolute value of -20 is ", abs_value)
Output:
The absolute value of -20 is 20
The abs() function takes -20 as an argument and returns 20.
Example 2: Absolute value of a floating point number
The following program returns an absolute value of -20.45:
#find the absolute valule of a floating point number (-20.45): abs_value = abs(-20.45) print ("The absolute value of -20.45 is ", abs_value)
Output:
The absolute value of -20.45 is 20.45
The abs() function takes a floating-point number -20.45 as an argument and returns 20.45.
Example 3: Absolute value of a floating point number (2)
The following program uses the __abs__() function to return an absolute value of -20.40:
#find the absolute valule of a floating point number (-20.45): number = -20.45 abs_value = number.__abs__() print ("The absolute value of -20.45 is ", abs_value)
Output:
The absolute value of -20.45 is 20.45
Here, the __abs__() function is used instead of abs().
Example 4: Absolute value of a complex number
The following code returns the absolute value of a complex number:
#Find the absolute valule of a complex number (5+2j): abs_value = abs(5+2j) print ("The absolute value of 5+2j is ", abs_value)
Output:
The absolute value of 5+2j is 5.385164807134504
Summary
In this tutorial, you learned how to find the absolute value of a number using the Python abs() function, which takes one numeric argument and returns its absolute value.