Absolute value

EasyIf-Else Programs · 53 of 64

Write a Python program to print the absolute value of a number.

Advertisement
Input
-1, 7
Output
-1 -> 1 | abs(): 1
7 -> 7 | abs(): 7

Approach

  1. If the number is negative, negate it; or use abs().

Solution

Python
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.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More if-else programs

← All 64 If-Else Programs