How to calculate absolute value in python
To get the absolute value of a number in python there is the “Built-in” function: abs():
1 2 3 4 5 | abs(number) number : Negative or Positive Number |
Example: Write a program to find absolute value of an input number in python.
1 2 3 4 5 6 7 | number = float(input("Enter a number:")) number=abs(number) print("Number:{}".format(number)) |
Output:
1 2 3 4 | Enter a number:-25 Number:25.0 |
Example 1: integer
1 2 3 4 5 | >>> x = - 3 >>> abs(x) 3 |
Example 2: float
1 2 3 4 5 | >>> x = - 6.0 >>> abs(x) 6.0 |
Example 3: complex
1 2 3 4 5 | >>> z = complex(3,4) >>> abs(z) 5.0 |
Example 4: mixed example
1 2 3 4 5 6 7 8 9 10 11 12 13 | # floating point number float = -54.26 print('Absolute value of float is:', abs(float)) # An integer int = -94 print('Absolute value of integer is:', abs(int)) # A complex number complex = (3 - 4j) print('Absolute value or Magnitude of complex is:', abs(complex)) |