Python Practice › If-Else Programs › Program 53
Absolute value
Write a Python program to print the absolute value of a number.
Input
-1, 7
Output
-1 -> 1 | abs(): 1 7 -> 7 | abs(): 7
Approach
- If the number is negative, negate it; or use
abs().
Solution
for n in [-1, 7]: if n < 0: result = -n else: result = n print(n, "->", result, "| abs():", abs(n))Output
-1 -> 1 | abs(): 1 7 -> 7 | abs(): 7
Line by line
Lines 2-5
Negating a negative number makes it positive.
Line 6
The built-in abs() gives the same result.
Learn the concept
New to this topic? Read the lesson, then come back.