Javaexercise.com

Python abs() Method: How to Find Absolute Value in Python

Python abs() method is a built-in method. It is used to get absolute value of a number. It returns absolute value of a number that can be an integer, float, or a complex value. It takes single argument and if the argument is a complex number, it returns magnitude of the number.


Signature

abs(x)


Parameter Description
x (Required) This argument can be an integer, float or a complex number.


Return Value

It returns an absolute value of the specified number.

  If the argument is an integer, it returns integer absolute value.

  If the argument is a floating point value, it returns float absolute value.

  If the argument is a complex number, it returns magnitude.


Error: It returns an error (TypeError), if the argument is not a number.


Example: Find Absolute Value in Python

Let’s first understand, how this method works and what it returns?

#abs() method
val1 = abs(12) #interger argument
val2 = abs(-12) #negative interger
#displaying result
print(val1)
print(val2)
Output:
 12
 12


Example: Find Absolute Value of Float Value in Python

#abs() method
val1 = abs(12.56) #float argument
val2 = abs(-12.56) #negative float
#displaying result
print(val1)
print(val2)
Output:
 12.56
 12.56


Example: Find Absolute Value of Complex Values in Python

If the argument is a complex number, method returns magnitude only. See, the below example.

#abs() method
val1 = abs(3+4j) #complex number
val2 = abs(3-4j)
#displaying result
print(val1)
print(val2)
Output:
 5.0
 5.0