Python Program to Swap Three Numbers

1. Introduction

Swapping numbers is a common exercise in programming to understand variable manipulation. While swapping two numbers is straightforward, swapping three numbers introduces a slightly more complex challenge. This task can help us delve deeper into the mechanics of assignment and value swapping in Python.

Swapping involves exchanging the values held by the variables. When we swap three numbers, we shift their values so that each number moves to the position of the next, with the last number going to the position of the first.

2. Program Steps

1. Define three numbers to be swapped.

2. Perform the swapping in a circular fashion.

3. Output the numbers after swapping.

3. Code Program

# Initialize three numbers
a = 10
b = 20
c = 30

# Print original values
print("Original values:")
print("a =", a)
print("b =", b)
print("c =", c)

# Swap the numbers in a circular fashion
# Here, we use Python's ability to assign multiple variables at once
a, b, c = c, a, b

# Print swapped values
print("\nSwapped values:")
print("a =", a)
print("b =", b)
print("c =", c)

Output:

Original values:
a = 10
b = 20
c = 30
Swapped values:
a = 30
b = 10
c = 20

Explanation:

1. a, b, and c are initialized with the values 10, 20, and 30 respectively.

2. The original values of a, b, and c are printed before the swap takes place.

3. The multiple assignment a, b, c = c, a, b changes the values of a, b, and c in a circular fashion. The value of c goes to a, a to b, and b to c.

4. The new swapped values are then printed, showing that the variables now hold the values 30, 10, and 20 respectively.

Comments