Founding Batch Offer ยท HLD ยท LLD ยท System Design at โ‚น799 until 30 Nov

Absolute Difference Check

Measure the gap between two numbers without keeping its sign. Students use Python abs, float subtraction, and a strict comparison with the threshold ten.

AdvancedPhase 1 - Level 5: Creative / Tricky Logical ScenariosExample 10 of 10
absolute-difference-check.py
1# Take two numbers
2num1 = float(input("Enter first number: "))
3num2 = float(input("Enter second number: "))
4
5# Calculate absolute difference
6diff = abs(num1 - num2)
7
8# Check
9if diff < 10:
10 print(f"Absolute difference ({diff}) is less than 10")
11else:
12 print(f"Absolute difference ({diff}) is not less than 10")

Output

Enter first number: 15
Enter second number: 20
Absolute difference (5.0) is less than 10

Enter first number: 15
Enter second number: 30
Absolute difference (15.0) is not less than 10

In this one

  • Measure unsigned distance
  • Use abs after subtraction
  • Distinguish < from <=

How it works

  1. 1

    Read num1 and num2.

  2. 2

    Store abs(num1 - num2) in diff.

  3. 3

    Compare diff with ten and print the message.

Edge cases

What if both inputs are equal?

What if both inputs are equal?

diff is zero, which is less than ten.

What happens for a gap of ten?

What happens for a gap of ten?

It prints that the difference is not less than ten.

What's going on

Subtracting in either order can change a sign, but abs keeps only the distance from zero. That makes diff the same nonnegative gap regardless of which input came first.

The code tests diff < 10, not <= 10. With 15 and 20, diff is 5.0 and the smaller-gap message prints. A gap of exactly ten belongs to the other branch. Floating-point inputs allow fractional gaps too.

What if both inputs are equal? diff is zero, which is less than ten.

What happens for a gap of ten? It prints that the difference is not less than ten.

Quiz

Tap an option. The answer stays hidden until you pick.

Question 1

Why call abs?

Pick an answer to check it.

Question 2

What if both inputs are equal?

Pick an answer to check it.

Questions people ask

What if both inputs are equal?

diff is zero, which is less than ten.

What happens for a gap of ten?

It prints that the difference is not less than ten.

Why call abs?

The direction of the subtraction should not affect the gap.