Python abs() function returns the absolute value of the number. It’s one of the built-in functions in python builtins module.
Table of Contents
Python Absolute Value using abs()
Python abs() takes a single argument, which has to be a number, and returns its absolute value.
- Integer, Long – returns absolute value.
- Float – returns absolute value.
- Complex – returns its magnitude
- Numbers in different formats – returns absolute value in decimal system even if numbers are defined in binary, octal, hexadecimal or exponential form.
Python abs() with integers
import sys
x = 5 # int
print(abs(x))
x = sys.maxsize # long
print(abs(x))
Output:
5
9223372036854775807
Python absolute value of float
x = 50.23434 # float
print(abs(x))
Output:
50.23434
Python abs() with complex numbers
x = 10 - 4j # complex
print(abs(x))
x = complex(10, 2) # another complex example
print(abs(x))
Output:
10.770329614269007
10.198039027185569
Python abs() with different format numbers
# numbers in different formats
x = 10.23e1/2 # exponential
print(abs(x))
x = 0b1010 # binary
print(abs(x))
x = 0o15 # octal
print(abs(x))
x = 0xF # hexadecimal
print(abs(x))
Output:
51.15
10
13
15
That’s all for quick examples of python absolute values of numbers using abs() function.
You can checkout complete python script and more Python examples from our GitHub Repository.
Reference: Official Documentation