abs() - Python Examples


Python - abs()

Python abs() builtin function is used to find the absolute value of a given number.

In this tutorial, you will learn the syntax of abs() function, and then its usage with the help of example programs.

Syntax

The syntax of abs() function is

abs(x)

where

ParameterDescription
xA number, or expression that evaluates to a number.

Examples

1. Absolute value of a 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}.')

Output

Absolute value of -523 is 523.

2. Absolute value of 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}.')

Output

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

3. Absolute value of a string - TypeError

If we provide an argument of any non-numeric type like string, abs() function raises TypeError.

Python Program

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

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.