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.

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
```

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,

**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
else:
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
```

- How to check the type of a variable in python?
- How to capitalize the first letter in python?
- What does len mean in python?
- How to sort tuples in python?
- How to check if a number is negative in python?
- How to check if a number is prime in python?
- What does ord() function do in python?
- How to shuffle a list in python?