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
1 2 3 4 5 6 7 |
import sys x = 5 # int print(abs(x)) x = sys.maxsize # long print(abs(x)) |
Output:
1 2 3 4 |
5 9223372036854775807 |
Python absolute value of float
1 2 3 4 |
x = 50.23434 # float print(abs(x)) |
Output:
1 2 3 |
50.23434 |
Python abs() with complex numbers
1 2 3 4 5 6 |
x = 10 - 4j # complex print(abs(x)) x = complex(10, 2) # another complex example print(abs(x)) |
Output:
1 2 3 4 |
10.770329614269007 10.198039027185569 |
Python abs() with different format numbers
1 2 3 4 5 6 7 8 9 10 11 |
# 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:
1 2 3 4 5 6 |
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