Home / Programs / Python program to swap two variables - By using arithmetic operators - Using multiplication and division operator
🚀 Programming Example

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

👁 241 Views
💻 Practical Program
📘 Step Learning

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

💻 Program Code

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)  
                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.