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 print("Enter 'x' for exit."); var1 = input("Enter value of variable1: "); if var1 == 'x': exit(); else: var2 = input("Enter value of variable2: "); print("\nSwapping of two variables started..."); temp = var1; var1 = var2; var2 = temp; print("Both the variables are successfully swapped!"); print("\nValue 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:
Above image shows the initial output asking from user to enter two variable's value to swap both the entered variable as shown in the below sample run.
Below is the same program on python shell: