ByteBoard Notes Notes

Find the absolute value of a number without using abs()

Computer Science XI · Experiment 04 of 27 · Python

11-CSPython programs
Expt. No.04
Page No.8

Absolute value without abs()

Aim

To write a Python program that finds the absolute value of a number without using the built-in function abs().

Concepts used

Algorithm

  1. Input a number.
  2. If the number is negative, its absolute value is the number multiplied by -1.
  3. Otherwise the absolute value is the number itself.
  4. Display the absolute value.

Program

# Find the absolute value of a number without abs() num = float(input("Enter a number: "))if num < 0:    absolute = -numelse:    absolute = numprint("Absolute value of", num, "is", absolute)

A marked line continues the line above it. In your file, write it on the same line.

Output

Run 1
$ python absolute_value.py
Enter a number: -17.5 Absolute value of -17.5 is 17.5
Run 2
$ python absolute_value.py
Enter a number: 9 Absolute value of 9.0 is 9.0

✓ Printed by running this program, not typed by hand.

Result

The absolute value of -17.5 was displayed as 17.5 and that of 9 as 9.0, which matches the definition |x| = x for x ≥ 0 and -x for x < 0.

Viva voce: what the examiner may ask

01What is the absolute value of a number?

Its distance from zero, so it is never negative: |-5| = 5 and |5| = 5.

02What does the unary minus in -num do?

It changes the sign of the value, so -(-17.5) becomes 17.5.

03What would abs(-17.5) return?

17.5. The program does the same job without the built-in function.

Variations for the lab test

  1. Find the absolute difference between two numbers.
  2. Check whether a number is positive, negative or zero.
  3. Use int() and test with -0.
! Common mistake Writing absolute = num - num or absolute = num * 1 for negative numbers: only multiplying by -1 (or unary minus) changes the sign.
Back to the 11-CS index