Python abs() – Absolute Value in Python

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:

  1. #find the absolute value of an integer number (-20):
  2. abs_value = abs(-20)
  3. 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:

  1. #find the absolute valule of a floating point number (-20.45):
  2. abs_value = abs(-20.45)
  3. 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:

  1. #find the absolute valule of a floating point number (-20.45):
  2. number = -20.45
  3. abs_value = number.__abs__()
  4. 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:

  1. #Find the absolute valule of a complex number (5+2j):
  2. abs_value = abs(5+2j)
  3. 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.


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