Python abs()

Python abs() function returns the absolute value of a number. This means it always gives you the positive version of the number, regardless of whether the original number was positive or negative. It’s handy for calculations where you only care about the magnitude, not the direction.

abs() Syntax

result = abs(number)
  • result: A variable to store the calculated absolute value.
  • abs(): The built-in Python function for finding absolute values.
  • number: The number of which you want to find the absolute value. This can be an integer, floating-point, or complex number.

Example 1: Finding the Absolute Value of a Negative Integer with Python abs()

number = -10
absolute_value = abs(number)
print(absolute_value)

Code Explanation

  • Line 1: Assign the value -10 to the variable number.
  • Line 2: Calls the abs() function with number as the argument. The absolute value (10 in this case) is stored in the absolute_value variable.
  • Line 3: Print the calculated absolute value to the console.

Output

10


Example 2: Finding the Absolute Value of a Floating-Point Number with Python abs()

number = 3.14159
absolute_value = abs(number)
print(absolute_value)

Code Explanation

  • Line 1: Assign the value 3.14159 to the variable number.
  • Line 2: Calls the abs() function. Since the original number is already positive, the absolute value remains unchanged.
  • Line 3: Prints the absolute value, the same as the original number in this case.

Output

3.14159


Example 3: Get the Magnitude of a Complex Number with Python abs()

complex_num = 3 + 4j 
magnitude = abs(complex_num)
print(magnitude)

Complex Number: A complex number is represented in the form a + bj, where:

  • a is the real part
  • b is the imaginary part
  • j represents the imaginary unit (√-1)

Magnitude: The magnitude of a complex number is its distance from the origin (0, 0) in the complex plane.

Code Explanation

  • Line 1: Assign the complex number 3 + 4j to the variable complex_num.
  • Line 2: The abs() function calculates the magnitude (or modulus) of the complex number using the formula sqrt(real_part^2 + imaginary_part^2).
  • Line 3: Prints the magnitude, which is 5.0 in this case.

Output

5.0


Also Read

Python all()