Python abs() – Examples

Python abs() Function – Find Absolute Value

Python abs() function can be used to calculate the absolute value of a number.

Syntax – abs()

The syntax of abs() function is

abs(x)

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

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

Example 1: abs() Function with Number

In this example, we will find the absolute value of a negative number.

Python Program

x = -523
absVal = abs(x)
print(f'Absolute value of {x} is {absVal}.')
Run

Output

Absolute value of -523 is 523.

Example 2: abs() Function with Numeric Expression

In this example, we will pass an expression to the abs() function, where the expression evaluates to a numeric value. abs() returns the absolute value of the expression’s resulting value.

Python Program

a = -523
b = 451
absVal = abs(a+b)
print(f'Absolute value of the expression (a+b) is {absVal}.')
Run

Output

Absolute value of the expression (a+b) is 72.

Example 3: String as argument to abs() – TypeError

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

Python Program

x = 'hello'
absVal = abs(x)
print(f'Absolute value of {x} is {absVal}.')
Run

Output

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

Summary

In this tutorial of Python Examples, we learned the syntax of abs() function, and how to find the absolute value of a number or a numeric expression using abs() function with examples.