The abs()
built-in Python function calculates absolute value of a number.
It takes one input x
.
- For negative numbers (
x < 0
) it returns-x
. - For positive numbers and zero (
x >= 0
) it returnsx
.
Input data types
Typical arguments to the abs()
function are int
or float
types.
>>> abs(3) 3 >>> abs(-3) 3 >>> abs(0) 0 >>> abs(3.5) 3.5 >>> abs(-3.5) 3.5
The argument to abs()
can be object of any class which implements the __abs__()
method, such as Decimal
or Fraction
:
>>> from decimal import Decimal >>> x = Decimal('-7.25') >>> x Decimal('-7.25') >>> abs(x) Decimal('7.25') >>> from fractions import Fraction >>> y = Fraction(-1, 3) >>> y Fraction(-1, 3) >>> abs(y) Fraction(1, 3)
The argument can't be a str
, tuple
, list
, set
, or dict
. These raise TypeError
.
>>> abs('-3.5') Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bad operand type for abs(): 'str' >>> abs((1, -1)) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: bad operand type for abs(): 'tuple'