Python program to swap two variables - By using arithmetic operators - Using multiplication and division operator

Python Operators in Python (Article) Operators in Python (Program)

150

Program:

P = int( input("Please enter value for P: "))  
Q = int( input("Please enter value for Q: "))  
   
# To Swap the values of two variables using Addition and subtraction operator  
P = P * Q    
Q = P / Q   
P = P / Q  
   
print ("The Value of P after swapping: ", P)  
print ("The Value of Q after swapping: ", Q)  

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

Explanation:

The code you provided performs a swap of the values of two variables, P and Q, using addition and subtraction operators. Here's how the code works:

  1. The user is prompted to enter a value for variable P using the input() function. The input() function waits for the user to enter a value and returns it as a string. Then, int() is used to convert the string input to an integer and assign it to the variable P. The same process is repeated for variable Q.

  2. The swap operation begins. The current value of P is multiplied by the value of Q and the result is assigned back to P. This step effectively stores the original value of P multiplied by the original value of Q in P.

  3. The current value of Q is obtained by dividing the new value of P (previously calculated) by the original value of Q. This step effectively stores the original value of P in Q.

  4. The new value of P is obtained by dividing the new value of P by the current value of Q. This step effectively stores the original value of Q in P.

  5. Finally, the swapped values of P and Q are printed using the print() function, along with appropriate messages.

In summary, this code performs a swap of two variables without using a temporary variable by utilizing multiplication, division, and the properties of mathematical operations.


This Particular section is dedicated to Programs only. If you want learn more about Python. Then you can visit below links to get more depth on this subject.