Exercises · Q15
Q.Write a program to swap two numbers without using a third variable.
Yanam BieapTextbookSubjective· 2mImportance★★★★★est
86% · 42/49 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 →Python's simultaneous assignment num1, num2 = num2, num1 swaps two variables in a single statement, no helper variable needed — 5 and 10 become 10 and 5.
The concept: in a tuple (simultaneous) assignment, Python evaluates the entire right-hand side first — capturing the current values (num2, num1) — and only then assigns them to the left-hand names. Nothing is overwritten prematurely, so no temporary variable is needed.
# Swap two numbers WITHOUT a third variable
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Before swapping:", num1, num2)
num1, num2 = num2, num1 # simultaneous assignment
print("After swapping: ", num1, num2)
Sample run:
Enter first number: 5
Enter second number: 10
Before swapping: 5 10
After swapping: 10 5
An alternative that also avoids a third variable — the arithmetic method — is worth knowing for exams:
num1 = num1 + num2 # num1 now holds the sum (15)
num2 = num1 - num2 # 15 - 10 = 5 -> old num1
num1 = num1 - num2 # 15 - 5 = 10 -> old num2
``` …
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.