Articles

Program to swap 2 variables using third variable in Python

Program to swap 2 variables using third variable in Python


In this python programming guide, we are going to learn

  • python program to swap two variables using third variable

Python program to swap two variables using third variable

The python program to exchange the values of two variables is as follows:

 

# Owner : TutorialsInhand Author : Devjeet Roy

a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = 0

print("Before swapping:")
print("a = {}, b = {}".format(a,b))

c = a
a = b
b = c

print("After swapping:")
print("a = {}, b = {}".format(a,b))

The output of the python program to exchange the values of two variables is as follows:

 

PS C:\Users\DEVJEET\Desktop\tutorialsInHand> python code.py
Enter a: 10
Enter b: 20
Before swapping:
a = 10, b = 20
After swapping:
a = 20, b = 10

Few important tips about this program

1. In this paradigm of swapping numbers, we reassign one number into the other variable such that we can swap it.

2. In the output, it is clearly seen that the numbers got interchanged.

3. The .format() is used to replace the braces with values of the variable passed to the function, in the string.

 

swap two numbers using third variable in python

 


Basic Python Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Devjeet Roy
Full Stack Web Developer & Data Science Enthusiast
Page Views :    Published Date : Feb 07,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!