Returns how far a number is from zero.
Synopsis
abs(number)
Description
abs removes the minus sign. It is useful for the distance between two numbers: abs(a - b).
Parameters
| Name | Meaning |
|---|---|
number |
An int or a float. |
Return value
The same type of number, never negative.
Example
print(abs(-5))
print(abs(3.5))
print(abs(2 - 10))
It prints:
5
3.5
8
Common mistake
n = input("Number: ")
print(abs(n))
Python stops with:
Number: -5
TypeError: bad operand type for abs(): 'str'
input returns a string. Convert it first: abs(int(n)).
See also
Last updated 2 weeks ago