Programs · Program 6-2
Q.Program 6-2: Program to print the positive difference of two numbers.
Odisha ChseTextbookSubjective· 2mImportance★★★★★est
10% · 4/39 Questions
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →Fix Program 6-1's negative result with two-way selection: if num1 > num2 subtract num2 from num1, else subtract the other way — the difference is now always non-negative.
The idea. Program 6-1 printed -5 for inputs 5 and 10 because it always computed num1 - num2. To report the positive difference we must decide at run time which number to subtract from which — the chapter's first real use of the if–else construct: one condition, two alternative computations, exactly one of which executes.
Program
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if num1 > num2:
diff = num1 - num2
else:
diff = num2 - num1
print("The positive difference of", num1, "and", num2, "is", diff)
Sample runs
Enter first number: 10
Enter second number: 5
The positive difference of 10 and 5 is 5
Enter first number: 5
Enter second number: 10
The positive difference of 5 and 10 is 5
Both input orders now give the same answer, 5 — the branch taken differs, the result does not.
Trace
| num1 | num2 | num1 > num2? | Branch | diff |
|---|---|---|---|---|
| 10 | 5 | True | if | 10 - 5 = 5 |
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.