Python programs · Basics
Python program to swap two numbers
Swapping exchanges the values of two variables. Python can do it in a single line, without a helper variable.
Approach
- Start with two variables.
- Use tuple assignment,
a, b = b, a. - Print both values to confirm the swap.
The program
a = 5 b = 9 print("Before:", a, b) a, b = b, a print("After:", a, b)
Sample run
Output
Before: 5 9 After: 9 5
How the code works
Python builds the pair (b, a) on the right-hand side before it assigns anything, so neither value is lost. In many other languages you need a third variable: temp = a, then a = b, then b = temp. That approach works in Python too, and it is worth trying once to see the steps.
Try changing it
- Swap three variables in a cycle:
a, b, c = b, c, a. - Read the two values with
input()instead of fixing them in the code.
Common mistakes
- Writing
a = band thenb = a, which leaves both variables with the same value. - Forgetting that the whole right-hand side is worked out first.