Python abs()

The abs() function is used to get the absolute value of a number. If a real number is passed as parameter to the function, it returns the absolute value of the number. If a complex number is passed as a parameter, the function calculates the magnitude of the number and returns the same.

``````abs(n) #Where n is a number
```
```

abs() Parameters:

abs method takes a mandatory single parameter. The parameter can be an integer, a floating point number or a complex number.

Parameter Description Required / Optional
number Numeric value    [integer/ float/complex] Required

abs() Return Value

The abs() function returns a positive number. For integers and floating point numbers the function returns its absolute value.
For complex numbers, the function returns the magnitude of the number

Input Return Value
Integer A positive value of Integer Number
Floating Number A positive value of Floating Number
Complex Number The magnitude of the complex number

Examples of abs() method in Python

Example 1 : abs() function over integer

``````
n = -5
print('Absolute value of -5 is:', abs(n))

n = 5
print('Absolute value of 5 is:', abs(n))
```
```

Output:

```
Absolute value of -5 is:5

Absolute value of 5 is:5
```

Example 2 : abs() over floating point

``````
n = -5.5
print('Absolute value of -5.5 is:', abs(n))

n = 5 .5
print('Absolute value of 5.5 is:', abs(n))
```
```

Output:

```
Absolute value of -5.5 is:5.5
Absolute value of 5.5 is:5.5
```

Example 3 : abs() over complex number

``````
n = -5 + 5j
print('Absolute value of -5+5j is:', abs(n)) n = 5 +5j
print('Absolute value of 5 +5j is:', abs(n))
```
```

Output:

```
Absolute value of -5+5j is: 7.07
Absolute value of 5+5j is: 7.07
```
VIEW ALL
VIEW ALL