The absolute value of any number is the modulus of that number, i.e., it will return the square root of the square of the number. It means that it will return only positive numbers even if you pass a negative number.
There is a built-in function available with a standard library of Python for finding absolute value, that is, abs() function. This abs() function returns the absolute value of the specified number. The number can be a negative integer, positive integer, floating-point number, or any complex number. It takes only one parameter as an argument, and that is the number.
Table of Contents
Here, the number is the input number whose absolute value we want to find. It can be a negative integer, positive integer, floating-point number, or any complex number.
- For both negative and positive integer values, it will return an absolute integer value.
- If we give floating-point numbers in argument, it will return absolute floating value.
- And for complex numbers, it will return the magnitude of that complex number.
Let’s have a look at some examples.
Case#01: When You Provide a Positive Integer in the Argument
When we input a positive integer to the abs() function, it will work as follows:
num = 6 abs_num = abs(num) print("abs(6) = " , abs_num)
Case#02: When You Give a Negative Integer in the Argument
num = -6 abs_num = abs(num) print("abs(-6) = " , abs_num)
We can see abs() is returning the absolute positive integer value of the provided negative integer.
Case#03: When You Pass a Negative Floating-Point Value in the Argument
num = -6.3 abs_num = abs(num) print("abs(-6.3) = " , abs_num)
Case#04: When You Give a Complex Number in the Argument
num1 = 6 num2 = 4j num = num1 + num2 abs_num = abs(num) print("abs(6+4j) = " , abs_num)
This article discussed how we could find the absolute value using the built-in abs() function in Python. In this method, the user has to pass a number as an argument to find its absolute value. Finally, we saw some examples in different scenarios.