Python abs() built-in function Tutorial. Calculate the absolute value of integer/float numbers and the magnitude of complex numbers using this method.
abs() is one of the Python’s built-in functions. It is used to calculate the absolute value of the provided number. In other words, you can calculate the magnitude of an integer, float or complex number using this function.
absoluteValue = abs(number)
This function only takes one argument which is the number whose absolute value you want to find out. The data type of this argument can be any one of the following listed.
- Complex Number
Using any other data type will raise
TypeError: bad operand type for abs().
abs() Return Value
The function, when provided a valid number in the argument, returns the magnitude of that number.
- For Integer and Float Values, it returns their positive values.
- For Complex Numbers, it returns the magnitude.
- For Boolean values, it returns 1 for True and 0 for False.
Have a look at the following examples to better understand the practical usage of the Python abs() built-in function.
Example 1. Calculating Positive Values of Integers & Floating-Point Numbers
#An Integer Number
aInteger = -5
#A Floating-Point Number
aFloatNumber = -12.25
#Finding absolute values
aIntegerPositive = abs(aInteger)
#Printing to console
print("Positive of aInteger = " + str(aIntegerPositive))
print("Positive of aFloatNumber = " + str(aFloatNumberPositive))
As the absolute value of any integer or floating-point number is simply their positive value, therefore, you can clearly see the output prints the corresponding positive values for provided negative integer and float number values.
Example 2. Calculating Magnitude of a Complex Number
#A Complex Number
complexNumber = 5 + 9j
#Finding Magnitude of the Complex Number
#Printing magnitude to console
print("Magnitude of " + str(complexNumber) + " is " + str(magnitude))
Here we’re simply finding out the magnitude of the complex number
5 + 9j using the abs() function.
Example 3. Calculating Absolute Numbers for Boolean Values
#A True Value
aTrue = True
#A False Value
aFalse = False
#Finding their corresponding numerical values
#and printing them to console
Here, you can clearly observe the output that the boolean values
False are respectively being converted into
I hope you found this guide useful. If so, do share it with others who are willing to learn Python. If you have any questions related to this article, feel free to ask us in the comments section.
And do not forget to subscribe to WTMatter!