Python 3 reference · Built-in Functions
Python abs() Function
Return the absolute value of a number: its distance from zero, so negative numbers become positive.
Python 3 Since 3.0
Syntax
abs(x)
Parameters
| Parameter | Description |
|---|---|
x |
An int, float or complex number (or any object with an __abs__() method). |
Return value
The absolute value, of the same numeric type. For a complex number, its magnitude as a float.
Examples
print(abs(-7))
print(abs(3.5))
print(abs(-0.25))
Output
7 3.5 0.25
# The distance between two temperatures, whichever is larger
today, yesterday = 18, 23
print(abs(today - yesterday))
Output
5
print(abs(3 + 4j)) # the length of the vector (3, 4)
Output
5.0
Good to know
abs()never changes the type of anintorfloat:abs(-2)is2,abs(-2.0)is2.0.- For a complex number it returns the magnitude
sqrt(real² + imag²), always afloat. - Your own classes can support
abs()by defining__abs__().
Version history
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
round()· Round a number to a given number of decimal places. Halfway values round to the nearest even number (banker's rounding).divmod()· Divide two numbers and return the quotient and the remainder together as a tuple: (a // b, a % b).pow()· Raise a number to a power, like base ** exp. With a third argument it computes the result modulo a number efficiently.- Python Numbers · tutorial
- Python Math · tutorial