Home / Programs / Python program to swap two variables
🚀 Programming Example

Python program to swap two variables

👁 286 Views
💻 Practical Program
📘 Step Learning
Python program to swap two variables

📌 Information & Algorithm

In 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.

💻 Program Code

P = int( input("Please enter value for P: "))  
Q = int( input("Please enter value for Q: "))  
   
# To swap the value of two variables  
# we will user third variable which is a temporary variable  
temp_1 = P  
P = Q  
Q = temp_1  
   
print ("The Value of P after swapping: ", P)  
print ("The Value of Q after swapping: ", Q)  
                        

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

📘 Explanation

In 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.
📚 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.