Note

Python - abs() - Get the absolute value of a number


Overview of the Python abs() function. Always get the positive value.

abs(number) is a built-in method that returns an absolute value of a provided number. It simply disregards the sign of the value and always makes it positive.

The input can be an integer, a float, or a complex number. For complex numbers, the abs() function returns the magnitude.

Take a look at examples below:


Using abs() with Integers

negative_int = -10
positive_int = 10

abs_negative_int = abs(negative_int)
abs_positive_int = abs(positive_int)

print(abs_negative_int)  # 10
print(abs_positive_int)  # 10

Output:

10
10

Using abs() with Floats

It also works with a float type values:

negative_float = -5.321
positive_float = 5.321

abs_negative_float = abs(negative_float)
abs_positive_float = abs(positive_float)

print(abs_negative_float)  # 5.321
print(abs_positive_float)  # 5.321

Output:

5.321
5.321

Using abs() with Complex Numbers

complex_number = 3 - 4j

magnitude = abs(complex_number)

print(magnitude)  # 5.0

Output:

5.0

Key Points to Remember about the abs() Function

  • Universal Applicability: Works with integers, floats, and complex numbers.

  • Positive Result: Always returns a positive value or magnitude.

  • Built-in Functionality: No need to import any module, abs() is a Python built-in function.

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: