Write Python. Understand every error.

Open the editor

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

  1. Start with two variables.
  2. Use tuple assignment, a, b = b, a.
  3. 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

Run this program in Py-CRAFT

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

Common mistakes

Learn the ideas

More programs

Share this page: