Python fabs

The Python fabs function returns the absolute value (positive value) of the specified expression or a specific number. In this section, we discuss how to use the fabs function to print the absolute value with an example.

The syntax of the fabs Function in Python Programming Language to find absolute values is

Math.fabs(number);

Number: It can be a number or a valid numerical expression for which you want to find absolute value.

  • If the number argument is a positive or negative number, the fabs function returns the absolute value.
  • If the number argument is not a number, the fabs function returns TypeError.

Python fabs Function Example

The fabs Function allows you to find the absolute values of numeric values. In this fabs example, we are going to find the absolute values of different data types and display the output.

First, we declared a tuple and a list. Next, we used the fabs Function directly on both the Positive integer and negative integer.

The first two Python statements find the corresponding absolute values, then we used the Function on Tuple and List items.

If you observe the above screenshot, the fabs function is working perfectly on them.

Next, We used the fabs Math function directly on multiple values. It means, FABS(10 + 20 – 40) = 10

Within the last statement, we tried the fabs Function on the String value, and it returns TypeError.

import math

Tup = (1, 2, 3, -4 , 5) # Tuple Declaration
Lis = [-1, 2, -3.5, -4 , 5] # List Declaration

print('Absolute value of Positive Number = %.2f' %math.fabs(10))
print('Absolute value of Negative Number = %.2f' %math.fabs(-15))

print('Absolute value of Tuple Item = %.2f' %math.fabs(Tup[3]))
print('Absolute value of List Item = %.2f' %math.fabs(Lis[2]))

print('Absolute value of Multiple Number = %.2f' %math.fabs(10 + 20 - 40))
print('Absolute value of String Number = ', math.fabs('Hello'))
Python FABS Function absolute value