In this tutorial, we will learn how to swap two variables in a Python program. Suppose we have two variables, P and Q; We have to write a Python program for swapping their values. We will also discuss the different methods in Python for doing this task.
P = int( input("Please enter value for P: "))
Q = int( input("Please enter value for Q: "))
# To swap the value of two variables
# we will user third variable which is a temporary variable
temp_1 = P
P = Q
Q = temp_1
print ("The Value of P after swapping: ", P)
print ("The Value of Q after swapping: ", Q)
Please enter value for P: 13
Please enter value for Q: 43
The Value of P after swapping: 43
The Value of Q after swapping: 13
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.