To swap two variables in python, first ask from user to enter the values of both the variables. Now swap two variables using the third variable say temp. After swapping both variables, if you wish to print the first variable, it will show the value of the second variable and if you wish to print the second variable, it will show the value of the first variable.
Following python program will ask from user to enter the two variable's value and swap the value of both the variable using the third variable. Finally print the result as output as shown below:
# Python Program - Swap Two Variables while True: print("Enter 'x' for exit.") var1 = input("Enter value of variable1: ") var2 = input("Enter value of variable2: ") if var1 == 'x': break else: temp = var1 var1 = var2 var2 = temp print("Value of First and Second Variable after swapping:") print("First Variable =",var1,"\nSecond Variable=",var2,"\n")
Here is the sample run of the above python program to illustrate how to swap two variables in python: