Skip to content
Exercises · Q14

Q.Write a program to swap two numbers using a third variable.

Puducherry CbseNCERTSubjective· 2mImportance★★★★★est
84% · 41/49 Questions
🔒 Locked · start free trial →

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 →

Save one value in a temporary variable before overwriting it: temp = num1; num1 = num2; num2 = temp — inputs 5 and 10 print as 10 and 5 after the swap.

The concept is assignment order: an assignment replaces a variable's old value, so writing num1 = num2 first would destroy num1's original value forever. The third variable exists purely to keep a copy of that value alive during the exchange.

# Swap two numbers using a third variable
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Before swapping:", num1, num2)

temp = num1      # step 1: park num1's value
num1 = num2      # step 2: num1 takes num2's value
num2 = temp      # step 3: num2 takes the parked value

print("After swapping: ", num1, num2)

Trace with num1 = 5, num2 = 10:

StepStatementnum1num2temp
start(inputs read)510—
1temp = num15105
2num1 = num210105

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.