Python Program - Swap Two Variables
here's a Python program that swaps the values of two variables:
# Define two variables a = 5 b = 10 # Print the original values print("Before swapping:") print("a =", a) print("b =", b) # Swap the values using a temporary variable temp = a a = b b = temp # Print the new values print("After swapping:") print("a =", a) print("b =", b)Sourwww:ec.theitroad.com
In this program, we define two variables called a
and b
(a=5
and b=10
).
To swap the values of the variables, we use a temporary variable called temp
. We assign the value of a
to temp
, then assign the value of b
to a
, and finally assign the value of temp
to b
.
We then print the new values of a
and b
using the print()
function and string formatting.
If we run this program, the output will be:
Before swapping: a = 5 b = 10 After swapping: a = 10 b = 5
Note that there are other ways to swap the values of two variables in Python, such as using tuple unpacking:
# Define two variables a = 5 b = 10 # Print the original values print("Before swapping:") print("a =", a) print("b =", b) # Swap the values using tuple unpacking a, b = b, a # Print the new values print("After swapping:") print("a =", a) print("b =", b)
This program produces the same output as the previous program, but uses tuple unpacking to swap the values of a
and b
.