Absolute value Python - Everything you need to knowIn 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.
Table of Contents - Absolute Value Python:
- Absolute Value Python
- How to use abs()
- Code and Explanation
- Closing thoughts
- Other Related Concepts
TL;DR - How to find the absolute value in Python?
Abs()is a built-in function that returns the absolute value of the argument.
print(abs(-10)) #Output = 10
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
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.
The Syntax of Python
#Absolute value Python abs(number)
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 ExplanationAdded below is the code used to find the absolute value of int, float, and complex numbers.
The output is as follows:
#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))
As you can see all the values have been converted into absolute values above. Feel free to try using the
10 10.1 14.142135623730951
abs()method with positive value.
Closing thoughts - Absolute value Python: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.