Contents
Python – abs()
Python abs() builtin function returns the absolute value of a given number.
Syntax
The syntax of abs()
function is
abs(x)
where x
can be a number, or expression that evaluates to a number.
Examples
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}.')
Run Output
Absolute value of -523 is 523.
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}.')
Run Output
Absolute value of the expression (a+b) is 72.
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}.')
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.