Create a Python program to swap two numbers taking runtime inputs. Swapping means interchanging, for instance, say we have two variables holding the following values
a = 10 &
b = 20 after swapping they will interchange the values so now
a = 20 &
b = 10.
Generally, a third variable is used for swapping where first we store the value of the first variable to a temporary variable say temp, then store the value of the second variable to the first variable and finally, store the value of the temporary variable to the second variable.
Fortunately, Python comes with a simple built-in method to swap two numbers without using any third variable.
a,b = b,a
This one-liner can swap values of two variable without using any additional variable, let’s see this in action in the program below.
- Take input from the user and store them in variables
- Print the values before swapping
- Print the values after swapping
num1 = input('Enter First Number: ') num2 = input('Enter Second Number: ') print("Value of num1 before swapping: ", num1) print("Value of num2 before swapping: ", num2) num1, num2 = num2, num1 print("Value of num1 after swapping: ", num1) print("Value of num2 after swapping: ", num2)
Runtime Test Cases
Enter First Number: 2 Enter Second Number: 3 Value of num1 before swapping: 2 Value of num2 before swapping: 3 Value of num1 after swapping: 3 Value of num2 after swapping: 2
The values inside the variables are interchanged; hence we swapped two numbers without using any third variable in Python.