Swap two variables

EasyBasic Programs · 8 of 40

Write a Python program to interchange (swap) the values of two variables.

Advertisement
Input
a = 10, b = 20
Output
a = 20
b = 10

Approach

  1. Use tuple unpacking a, b = b, a, or a temporary variable.

Solution 1: tuple unpacking

Python
a = 10b = 20 a, b = b, aprint("a =", a)print("b =", b)
Output
a = 20
b = 10

Line by line

Line 4

The right side b, a is evaluated first as the tuple (20, 10) and then unpacked into a and b, so no temporary variable is needed.

Solution 2: temporary variable

Python
a = 10b = 20 temp = aa = bb = tempprint("a =", a, "b =", b)
Output
a = 20 b = 10

Line by line

Lines 4-6

temp keeps the old value of a before it is overwritten. This is how swapping works in most other languages.

Learn the concept

New to this topic? Read the lesson, then come back.

More basic programs

← All 40 Basic Programs

Leave a Comment