Home / Programs / Python program to swap two variables - By using arithmetic operators - addition and Subtraction operator
Programming Example

Python program to swap two variables - By using arithmetic operators - addition and Subtraction operator

👁 272 Views
💻 Practical Program
📘 Step by Step Learning
Python program to swap two variables - By using arithmetic operators - addition and Subtraction operator

Information & Algorithm

In this method, we can swap values of both the variable in two ways:

  • Using addition and Subtraction 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)  

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

Explanation

No

How to learn from this program

First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.