DEV Community

hrishikesh1990
hrishikesh1990

Posted on • Originally published at flexiple.com

Absolute value Python - Everything you need to know

In this short tutorial, we cover the basics of the abs() Absolute value Python function. We look at how to use it along with a few real-world examples

This tutorial is a part of our initiative at Flexiple, to write short curated tutorials around often used or interesting concepts.

Table of Contents

TL;DR

Abs() is a built-in function that returns the absolute value of the argument.

print(abs(-10))

#Output = 10
Enter fullscreen mode Exit fullscreen mode

Absolute Value Python:

Absolute values in Python are used to return the absolute value of a number. What this essentially means is when a negative value is passed as an argument (eg: -10), Python returns its relevant positive number (eg: 10).

To understand how it works we must first understand what absolute value actually means. Absolute value is the distance between any number and 0 on the number line. These values are used extensively in the fields of Mathematics, Data Science, Physics, etc. However, developers generally use it to remove negative signs.

In an off case that a positive number or 0 is passed as an argument, Python returns the same value. This is because that is the actual distance from the 0 on the number line.

How to use abs()?:

The absolute value is calculated using the abs() built-in function. There are other methods to do this as well, however, since abs() is an inbuilt method we recommend using it.

Syntax of Python abs():

#Absolute value Python
abs(number)
Enter fullscreen mode Exit fullscreen mode

Here, “number” could either be an integer, float, or even a complex number. However, the latter returns the magnitude instead of the absolute value.

In case a floating value is passed, it returns an absolute float value.

Code and Explanation:

Added below is the code used to find the absolute value of int, float, and complex numbers.

#Absolute Value Python

#abs() on Integer values
print(abs(-10))

#abs() on Float values
print(abs(-10.10))

#abs() on Complex numbers
print(abs(10-10j))
Enter fullscreen mode Exit fullscreen mode

The output of this code is:

10
10.1
14.142135623730951
Enter fullscreen mode Exit fullscreen mode

As you can see all the values have been converted into absolute values above. Feel free to try using the abs() method with positive value.

Closing thoughts:

Along with its extensive use in the fields of Maths & Physics, absolute value has a few other use cases as well. A common example is while using a navigator to calculate the distance to a location. This is done by subtracting the distance traveled from the total distance. This value would be a negative value and the abs() method is used to display the value

Do let me know your thoughts in the comments section below. :)

Top comments (0)