What is abs() Function in Python?
The abs() function in Python is used to get the absolute value of a number, which means it gets rid of the number’s negative sign. In this tutorial, we’ll talk about what the abs() function in Python is, how to use it, and some examples.
The abs() function calculates the absolute value of its input argument. It returns either the positive or negative value of the input argument.
abs() Syntax
The syntax of the abs() function in Python is as follows:
abs(n)
abs() Parameters
Parameter | Description |
---|---|
n | Required a number. |
A number whose absolute value should be returned. It can be an integer, a float number, or a complex number.
abs() Return Value
The abs() function takes a number and gives back its absolute value.
- For integer numbers – an absolute number of integers is returned.
- For floating numbers – the absolute value of the floating number is returned.
- For complex numbers – the number’s size is returned.
If you want to test the Python code in this lesson, you will need to use a code editor like PyCharm. But if you want to run this code online, we also have a free Online Compiler in Python that you can use to test your Python code.
How to use the abs() function in Python?
To use the abs() function in Python, you need only one argument, which is the only one it can take. An argument is always a number that can be either positive or negative.
This number could be:
- A whole number, like 4, -15, or 10.
- A number that can change, like 4.1, -15.06, or 2.13.
- A tricky number. A complex number has two parts: a real part that is a real number, like 1 or 4, and an imaginary part that is not real.
In Python, the imaginary part is made by adding the letter j as a suffix, not the letter I as it is in Mathematics. You add j to the end of a real number, like 1j or 4j. So, 2 + 4j or 1 + 2j is an example of a complex number in Python.
Example of abs() function in Python
In this example, we give the abs() function float, int, and complex data, and it gives us back the absolute value.
Example 1
Example 2
The equation below shows how speed, distance traveled, and time was taken are related. And since time, distance, and speed can never be negative, we’ll use the abs() method to figure out the exact time, distance, and speed.
Distance = Speed * Time Time = Distance / Speed Speed = Distance / Time
Conclusion
In this tutorial, we’ve discussed the abs() function in Python can be used to change a floating-point number or an integer into an absolute value. This is especially helpful when you want to find the difference between two values.
By the way, if you want additional knowledge about built-in functions in Python you can check out our article about Complete Python Built-in Functions with Syntax and Examples.
Finally, I hope this lesson has helped you learn what is abs() function and its uses. Check out our list of Python Tutorial Topics if you missed any of our previous lessons.