How to Find the Absolute Value of a Number in Python?

In Python, you can get the absolute value of number by using the abs() method. It can be used with the following:

  1. Integers;
  2. Floats;
  3. Complex numbers;
  4. Objects implementing __abs__().

Integer Absolute Value

You can get an integer in absolute form in the following way:

print(abs(1234)) #=> 1234
print(abs(-1234)) #=> 1234

Floating Point Absolute Value

You can pass a floating point number to the abs() method, for example, like so:

print(abs(12.34)) #=> 12.34
print(abs(-12.34)) #=> 12.34

Complex Number Absolute Value

You can use the abs() method with a complex number, which would return its magnitude:

# complex numbers
print(abs(1234j)) #=> 1234.0
print(abs(-1234j)) #=> 1234.0

Object Absolute Value

If an object implements the __abs__() method, then can pass it to the abs() method.

For example, you could create a "NumericStr" class that accepts numeric strings as value. You can define how these values are converted to their absolute form by implementing the __abs__() method, like so:

class NumericStr:
    def __init__(self, value):
        self.value = value

    def __abs__(self):
        return self.value.replace('-', '')

num1 = NumericStr('1234')
num2 = NumericStr('-1234')

print(abs(num1)) #=> '1234'
print(abs(num2)) #=> '1234'

Without such an implementation, using a numeric string with the abs() method would not possible as it only accepts numbers:

# TypeError: bad operand type for abs(): 'str'

If the object does not implement the __abs__() method, and you pass it to the abs() method, then it will raise an error:

class NumericStr:
    def __init__(self, value):
        self.value = value

# TypeError: bad operand type for abs(): 'NumericStr'

Hope you found this post useful. It was published . Please show your love and support by sharing this post.