To swap two numbers in python, you have to ask from user to enter value of two numbers to swap those two numbers using the third variable. Swapping of two number means placing the value of first variable to second variable and the value of second variable to the first variable just by using another temporary variable.
Following python program will ask from the user to enter the value of two numbers to swap both the number.
To swap two numbers in python, first store the value of the first number to a temporary variable say swap, then store the value of the second variable to the first variable, and finally store the value of the temporary variable say swap to the second variable as shown in the program given below:
# Python Program - Swap Two Numbers while True: print("Enter 'x' for exit.") num1 = input("Enter first number: ") num2 = input("Enter second number: ") if num1 == 'x': break else: number1 = int(num1) number2 = int(num2) swap = number1 number1 = number2 number2 = swap print("Value of First and Second number after swapping:") print("First Number =",number1,"\nSecond Number=",number2,"\n")
Here is the sample run of the above python program to show how to swap two numbers in python:
You may also like to learn or practice the same program in other popular programming languages: