Python Program to Find Absolute Value
Use the built-in function
abs() in Python to find the absolute value of a number, for example, abs(-5) returns 5.Examples
Input-10
Output10
Input0
Output0
Input7
Output7
How to Think About It
To find the absolute value, think about removing any negative sign from the number. If the number is negative, make it positive; if it is already positive or zero, keep it as is. This gives the distance of the number from zero on the number line.
Algorithm
1
Get the input number.2
Check if the number is less than zero.3
If yes, multiply the number by -1 to make it positive.4
If no, keep the number as it is.5
Return the resulting positive number.Code
python
number = float(input('Enter a number: ')) absolute_value = abs(number) print('Absolute value:', absolute_value)
Output
Enter a number: -8
Absolute value: 8.0
Dry Run
Let's trace the input -8 through the code
1
Input number
User enters -8, so number = -8.0
2
Calculate absolute value
abs(-8.0) returns 8.0
3
Print result
Prints 'Absolute value: 8.0'
| Step | Variable | Value |
|---|---|---|
| 1 | number | -8.0 |
| 2 | absolute_value | 8.0 |
Why This Works
Step 1: Input number
The program reads the number entered by the user as a floating-point value.
Step 2: Use abs() function
The built-in abs() function returns the absolute value by removing any negative sign.
Step 3: Output result
The program prints the absolute value, showing the positive distance from zero.
Alternative Approaches
Using conditional statement
python
number = float(input('Enter a number: ')) if number < 0: absolute_value = -number else: absolute_value = number print('Absolute value:', absolute_value)
This method manually checks the sign and converts negative numbers to positive, useful if you want to avoid built-in functions.
Using math module
python
import math number = float(input('Enter a number: ')) absolute_value = math.fabs(number) print('Absolute value:', absolute_value)
The <code>math.fabs()</code> function returns the absolute value as a float, similar to <code>abs()</code> but always returns float.
Complexity: O(1) time, O(1) space
Time Complexity
Finding the absolute value is a single operation with no loops, so it runs in constant time O(1).
Space Complexity
The program uses a fixed amount of memory for variables, so space complexity is O(1).
Which Approach is Fastest?
Using the built-in abs() is fastest and most readable; manual condition checks add unnecessary code.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Built-in abs() | O(1) | O(1) | Simplicity and speed |
| Conditional check | O(1) | O(1) | Understanding logic without built-ins |
| math.fabs() | O(1) | O(1) | When working with math module functions |
Use Python's built-in
abs() function for a simple and efficient way to get absolute values.Forgetting to handle negative numbers and returning the original number without converting it to positive.