Programming Examples
Python program to input two number and swap them
Write a program to input two number and swap them.
Solution 1: Using Multiple Assignment
n1=int(input("Enter number 1 : "))
n2=int(input("Enter number 2 : "))
print("Original Number : ",n1,n2)
n1,n2=n2,n1
print("After Swapping : ",n1,n2)
Solution 2: Swapping by using 3rd variable
n1=int(input("Enter number 1 : "))
n2=int(input("Enter number 2 : "))
print("Original Number : ",n1,n2)
n3=n1
n1=n2
n2=n3
print("After Swapping : ",n1,n2)
Solution 3: Swapping by using Arithmetic Addition and Subtraction
n1=int(input("Enter number 1 : "))
n2=int(input("Enter number 2 : "))
print("Original Number : ",n1,n2)
n1=n1+n2
n2=n1-n2
n1=n1-n2
print("After Swapping : ",n1,n2)
Solution 4: Swapping by using Arithmetic Multiplication and Division
n1=int(input("Enter number 1 : "))
n2=int(input("Enter number 2 : "))
print("Original Number : ",n1,n2)
n1=n1*n2
n2=n1/n2
n1=n1/n2
print("After Swapping : ",n1,n2)
Output/ Explanation:
Enter number 1 : 45
Enter number 2 : 30
Original Number :Â 45 30
After Swapping :Â 30 45