Python program to swap two variables

Python program to swap two variables. We are here presenting two method of swapping the two variables. It is asked in CBSE class 11, 12 and B Tech Computer science courses.

Aim: Write a python program to swap two variables.

Method 1 : By using temporary variable.

  • Enter the variables P and Q.
  • A temporary variable will be assigned the value of P.
  • Q variable is assigned to P.
  • Then temporary variable value is given to Q.

Source 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)  

Output Method 1 :

Output Explaination:

Two values, in two variable is captured. (Please enter value for P:, Please enter value of Q:)
After swapping, The value of p after swapping : and The value of q after swapping.

Method 2 : By using comma operator

  • First the two variable P and Q are entered.
  • Swapping is done by comma operator given P,Q = Q,P.
  • Then they are output of the newly swapped variable P and Q.
P = int( input("Please enter value for P: "))  
Q = int( input("Please enter value for Q: "))  
   
# To Swap the values of two variables  
P, Q = Q, P  
   
print ("The Value of P after swapping: ", P)  
print ("The Value of Q after swapping: ", Q)

Output Method 2:

Output Method 2 Explanation:

Two values, in two variable is captured. (Please enter value for P:, Please enter value of Q
After swapping, The value of p after swapping : and The value of q after swapping.

Thank you for reading and learning from this Python program to swap two variables.. We are here presenting two method of swapping the two variables. It is asked in class 11, 12 and B Tech Computer science courses. It is a basic program. Programming skills have to be nurtured everyday to become a nice programmer. This below are some links for more programming question.

Python Programs Archives – CS Study

Computer Science with Python Practical Book Solutions Class 11 Term -2 – CS Study

Computer Science Practical file for class 12 Term-2 – CS Study

Leave a Comment

Your email address will not be published. Required fields are marked *

Exit mobile version