Python abs() Function

Python Abs() Function

Python abs() built-in function Tutorial. Calculate the absolute value of integer/float numbers and the magnitude of complex numbers using this method.

Python abs() Function

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.

Syntax

abs() Parameters

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.

  • Integer
  • Float
  • Complex Number
  • Boolean

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.

Examples

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

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.

Python Abs() Function Example Integers & Float Numbers Positive Or Absolute Value Calculation

Example 2. Calculating Magnitude of a Complex Number

Here we’re simply finding out the magnitude of the complex number 5 + 9j using the abs() function.

Python Abs() Method Example Calculating Magnitude Of Complex Numbers

Example 3. Calculating Absolute Numbers for Boolean Values

Here, you can clearly observe the output that the boolean values True and False are respectively being converted into 1 and 0.

Python Abs() Built In Function Example For Boolean Values Conversion To Numbers 0 And 1

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!

Subscribe To WTMatter!

Receive updates of our latest articles via email. Enter your email address below to get started.

Leave a Reply

Your email address will not be published. Required fields are marked *