Python abs() Function

Python abs() Function

A built-in Python function that gets used a lot in computational work is the abs() function. The abs() function accepts a numeric value as input and returns the absolute value of that input. The absolute value refers to the non-negative value of a number. So for example the absolute value of -10 is 10. The absolute value of 10 is also 10. In this tutorial, we will look at examples of how to use the abs() function in some small Python programs.

Python abs() Example One

We’ll use Jupyter Notebook to run these examples since it is a great tool for quick and easy code tests. This first example uses the abs() function accepting the input of the integer 80. In the output, we see that the absolute value of 80 is 80.

python abs example one

Python abs() Example Two

In example two of the abs() function we can use the abs() function once again. This time we pass a negative integer to the abs() function. That negative integer is -75. In the output, we see that the absolute value of -75 is 75.

python abs example two

Python abs() Example Three

The third example of Python abs() is an example of getting the absolute value of a temperature. That means that this time, we are passing in a floating-point value since it has a decimal place. The result is the same, abs() shows that the absolute value of 98.6 is 98.6. Fantastic.

abs example python

Python abs() Example Four

Perhaps you live in an area where you are un(lucky) enough to experience temperatures that go into a negative value. In this fourth example of Python abs(), we initialize another temperature variable to a bone-chilling negative 27.5. Then we pass that negative floating-point value to the abs() function. The result is that the absolute value of -27.5 is 27.5. Not exactly warm, but manageable!

abs function python

Python abs() Example Five

Example five shows how to use the abs() function when doing a calculation that requires absolute values. This example calculates the manhattan distance between two points, which is the distance between points measured along axes at right angles. It is the distance that would be traveled to get from one point to the other if a grid-like path is taken. Let’s see this in action using the abs() function to help us out.

abs python manhattan distance

Python abs() Example Six

The abs() function also works on complex numbers. These are numbers such as 5 + 7j or 9 – 3j. Let’s see an example of how abs() treats these values.

python abs complex numbers

Python abs() Function Summary

The abs() function is used to get the absolute value of a numerical value in Python. It works on integers, floating-point numbers, and also complex numbers as we saw in all of the examples above.