How to get absolute value in Python?

In mathematics, the absolute value of a number is its distance from 0. The absolute value or modulus |x| of a real number x is a non-negative quantity. For example, the absolute value of |-5| is 5.

Getting the absolute value using abs() function

In Python, abs() is a built-in function that takes a number as an argument and returns the absolute value of the number. For a complex number, abs() return its magnitude.

num_1 = -9
print("Absolute value of -9: ", abs(num_1))
num_2 = 9
print("Absolute value of 9: ", abs(num_2))
complex_1 = 3 + 4j
print("Absolute value of 3 + 4j: ", abs(complex_1))

The above code returns the output as

Absolute value of -9:  9
Absolute value of 9:  9
Absolute value of 3 + 4j:  5.0

Getting the absolute value using the If else statement

Let us consider a user-defined function absolute that takes a number num as a parameter. The isinstance(num, complex) checks if the num is an object of the complex number. If the condition is True, the magnitude of a complex number is returned.

In mathematics, the magnitude of the complex number is calculated as,complex-absolute-value

num.real and num.imag returns the real and imaginary part of the complex number respectively. The math.sqrt performs the square root operation of (num.real**2 + num.imag**2) and returns the magnitude. If the number is less than 0(negative) and is not a complex number then, -num is returned, else the num value is returned.

import math
def absolute(num):
    if (isinstance(num, complex)):
        return (math.sqrt(num.real**2 + num.imag**2))
    elif num<0:
        return -num
        return num
print("Absolute value of -9: ", absolute(-9))
print("Absolute value of  9: ", absolute(9))
print("Absolute value of 3+ 4j: ", absolute(3 + 4j))

The above code gives the output as

Absolute value of -9:  9
Absolute value of  9:  9
Absolute value of 3+ 4j:  5.0
0 results
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions