Python Glossary Русский

all Python 3Arithmetic & operatorsfunction

abs()

numbers

Built-in function that returns the absolute value (magnitude) of a number. Works with int, float and complex.

Syntax

abs(x)

The result type follows the argument: int gives int, float gives float, and complex gives float, since that is a vector length rather than a sign-stripped number. The familiar abs(a - b) < 1e-9 idiom for comparing floats only holds near 1: at large magnitudes such a fixed absolute tolerance always fails, so reach for math.isclose() with its relative tolerance instead.

Examples

print(abs(-7))  # → 7
print(abs(3.14))  # → 3.14
print(abs(-0.0))  # → 0.0
print(abs(3 + 4j))  # → 5.0 (модуль комплексного числа)
nums = [-3, 1, -5, 2]
print(max(nums, key=abs))  # → -5 (наибольший по модулю)

See also

Open in the full glossarydocs.python.orgReport an inaccuracy