Question :
Swap two variables without using a third temporary variable
Program:
1 2 3 4 5 |
num1= int(input("Enter the first number:")) num2=int(input("Enter the second number:")) print "num1:",num1,"num2:", num2 num1,num2=num2,num1 print "After swap: num1:",num1,"num2:", num2 |
Explanation:
Here num1, num2 acts as a tuple. Since tuples are mutable, the above assignment works perfectly well
Output:
1 2 3 4 |
Enter the first number:8 Enter the second number:99 num1: 8 num2: 99 After swap: num1: 99 num2: 8 |
Leave a Reply