Python abs() – Absolute Value in Python

How to Get the Absolute Value of a Number using the Python abs() function

In this tutorial, you'll learn how to get the absolute value of a number using the Python abs() function. The abs() function 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: Can be an integer or a floating-point number

Remark

  • If the number argument is a complex number, abs() return its magnitude.

abs() Examples

Example 1: Absolute Value of an Integer Number

The following program returns the absolution of -20:

#find the absolute value of an integer number (-20):
abs_value = abs(-20)
print ("The absolute value of -20 is ", abs_value)

Result:

The absolute value of -20 is 20

Here, abs() takes -20 as the argument and returns 20.

Example 2: Absolute Value of a Floating Number

The following program returns the 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)

Result:

The absolute value of -20.45 is 20.45

Here, abs() takes a floating-point number -20.45 as the argument and returns 20.45.

Example 3: Absolute Value of a Floating Number (2)

The following program returns the absolute value of -20.40 using the __abs__() function:

#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)

Result:

The absolute value of -20.45 is 20.45

Here, we use the __abs__() function 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)

Result:

The absolute value of 5+2j is 5.385164807134504

In this tutorial, you've learned how to get the absolute value of a number using the abs() function in Python. The abs() function takes one argument that is a number and then returns the absolute value.


See also:
Python return Statement with Examples
Python List Methods and Functions with Examples
Python Factorial – Find the Factorial of a Number
Python min() – Find the Smallest Value in Python
Python max() Function – Find the Largest Value in Python

Leave a Comment