abs() Function in Python

Python abs() Function

The Python abs() function is a built-in mathematical function that returns the absolute value of a number. It is commonly used to obtain the positive magnitude of a numeric value, regardless of whether it is positive or negative. The syntax for using the abs() function is straightforward:

abs(x)

Here, x represents the number for which you want to find the absolute value. The abs() function takes a single argument and returns the absolute value as the output.

Key Points about the abs() Function:

  1. The abs() function can be applied to integers, floating-point numbers, and complex numbers.
  2. When the input is an integer or a floating-point number, the function returns the positive value of that number.
  3. For complex numbers, the abs() function returns their magnitude, which is the distance from the origin (0,0) in the complex plane.
  4. The result of the abs() function is always a non-negative value.

Example:

print(abs(-5))      # Output: 5
print(abs(3.14))    # Output: 3.14
print(abs(0))       # Output: 0
print(abs(2 + 3j))  # Output: 3.605551275463989

In the above examples, the abs() function is used to calculate the absolute values of different numbers, including both real and complex values.

Remember, the abs() function is a handy tool when you need to ensure that you are working with positive values or need to find the magnitude of a complex number.