Python Absolute Value – abs()

Python Absolute Value

In Python, Absolute Value can be calculated using abs() function.

The syntax of abs() function is:

abs( x )

where x can a number, or expression that evaluates to a number.

abs() function returns the absolute value of the argument provided.

Example – Python abs() – With Number

Let us find the absolute value of a negative number.

x = -523
absVal = abs(x)

print("Absolute value of", x, "is", absVal)
Run this program ONLINE

Output

Absolute value of -523 is 523

Example – Python abs() – With Numeric Expression

Let us find the absolute value of a numeric expression.

a = -523
b = 451
absVal = abs(a+b)

print("Absolute value of (a+b)", "is", absVal)
Run this program ONLINE

Output

Absolute value of (a+b) is 72

Example – String as argument to abs() – TypeError

If you provide any other argument of type other than number, you will get TypeError.

x = 'hello'
absVal = abs(x)

print("Absolute value of (a+b)", "is", absVal)
Run this program ONLINE

Output

Traceback (most recent call last):
  File "example1.py", line 2, in <module>
    absVal = abs(x)
TypeError: bad operand type for abs(): 'str'

Summary

We learned to find the absolute value of a number or a numeric expression using abs() function of Python.