Write a program to swap two numbers in python
Swapping By using the comma operator Swapping By using Naive Approach Swapping By using arithmetic operatorsSwapping in Python By using the comma operator
1 2 3 4 5 6 7 8 |
T4tutorials_1 = int( input("Please enter a value for T4tutorials_1: ")) T4tutorials_2 = int( input("Please enter a value for T4tutorials_2: ")) # To Swap the values of two variables T4tutorials_1, T4tutorials_2 = T4tutorials_2, T4tutorials_1 print ("The Value of T4tutorials_1 after swapping: ", T4tutorials_1) print ("The Value of T4tutorials_2 after swapping: ", T4tutorials_2) |
Swapping in Python By using Naive Approach
1 2 3 4 5 6 7 8 9 10 11 |
T4tutorials_1 = int( input("Please enter a value for T4tutorials_1: ")) T4tutorials_2 = int( input("Please enter a value for T4tutorials_2: ")) # To swap the value of two variables # we will user third variable which is a temporary variable temp_1 = T4tutorials_1 T4tutorials_1 = T4tutorials_2 T4tutorials_2 = temp_1 print ("The Value of P after swapping: ", T4tutorials_1) print ("The Value of T4tutorials_2 after swapping: ", T4tutorials_2) |
Swapping in Python By using arithmetic operators
1 2 3 4 5 6 7 8 9 10 |
T4tutorials_1 = int( input("Please enter a value for T4tutorials_1: ")) T4tutorials_2 = int( input("Please enter a value for T4tutorials_2: ")) # To Swap the values of two variables using Addition and subtraction operator T4tutorials_1 = T4tutorials_1 + T4tutorials_2 T4tutorials_2 = T4tutorials_1 - T4tutorials_2 T4tutorials_1 = T4tutorials_1 - T4tutorials_2 print ("The Value of T4tutorials_1 after swapping: ", T4tutorials_1) print ("The Value of T4tutorials_2 after swapping: ", T4tutorials_2) |
Swapping in Python By using XOR
1 2 3 4 5 6 7 8 9 10 |
T4tutorials_1 = int( input("Please enter a value for T4tutorials_1: ")) T4tutorials_2 = int( input("Please enter a value for T4tutorials_2: ")) # To Swap the values of two variables using XOR T4tutorials_1 = T4tutorials_1 ^ T4tutorials_2 T4tutorials_2 = T4tutorials_1 ^ T4tutorials_2 T4tutorials_1 = T4tutorials_1 ^ T4tutorials_2 print ("The Value of T4tutorials_1 after swapping: ", T4tutorials_1) print ("The Value of T4tutorials_2 after swapping: ", T4tutorials_2) |
Please enter a value for T4tutorials_1: 6
Please enter a value for T4tutorials_2: 3
The Value of T4tutorials_1 after swapping: 3
The Value of T4tutorials_2 after swapping: 6
Swapping in Python By using multiplication and division operator
1 2 3 4 5 6 7 8 9 10 |
T4tutorials_1 = int( input("Please enter a value for T4tutorials_1: ")) T4tutorials_2 = int( input("Please enter a value for T4tutorials_2: ")) # To Swap the values of two variables using Addition and subtraction operator T4tutorials_1 = T4tutorials_1 * T4tutorials_2 T4tutorials_2 = T4tutorials_1 / T4tutorials_2 T4tutorials_1 = T4tutorials_1 / T4tutorials_2 print ("The Value of T4tutorials_1 after swapping: ", T4tutorials_1) print ("The Value of T4tutorials_2 after swapping: ", T4tutorials_2) |