Python program to swap two variablesIn this tutorial, we will learn how to swap two variables in a Python program. Suppose we have two variables, P and Q; We have to write a Python program for swapping their values. We will also discuss the different methods in Python for doing this task. Method 1: By using Naïve ApproachIn this method, the naïve approach will store the value of the P variable in a temporary variable, and then it will assign the variable P with the value of the Q variable. Then, it will assign the value of the temporary variable to the Q variable, which will result in swapping the values of both the variable. Example: Output: Please enter value for P: 13 Please enter value for Q: 43 The Value of P after swapping: 43 The Value of Q after swapping: 13 Method 2: By using comma operatorWe can use the comma operator. We do not need to use a third variable for swapping the values of two variables for this method. Example: Output: Please enter value for P: 12 Please enter value for Q: 43 The Value of P after swapping: 43 The Value of Q after swapping: 12 Method 3: By using XOR methodWe can also use the bitwise XOR method for swapping two variables. The XOR of two variables, P and Q, will return the number which has all the bits as 1 whenever the bits of the P and Q variables differ. Such as XOR of 4 (in binary 0100) and 6 (in binary 0110) is 1010. XOR of 2 (in binary 0010) and 8 (in binary 1000) is 1010. Example: Output: Please enter value for P: 12 Please enter value for Q: 10 The Value of P after swapping: 10 The Value of Q after swapping: 12 Method 4: By using arithmetic operatorsIn this method, we can swap values of both the variable in two ways:
Example: Output: Please enter value for P: 15 Please enter value for Q: 43 The Value of P after swapping: 43 The Value of Q after swapping: 15
Example: Output: Please enter value for P: 23 Please enter value for Q: 14 The Value of P after swapping: 14.0 The Value of Q after swapping: 23.0 ConclusionIn this tutorial, we have discussed various methods to swap the value of two variables in the Python program. Next TopicPython Generate a Random Number |
We provides tutorials and interview questions of all technology like java tutorial, android, java frameworks
G-13, 2nd Floor, Sec-3, Noida, UP, 201301, India