Articles

Program to swap two variables without using third variable in python

Program to swap two variables without using third variable in python


In the python programming guide, we will learn to write

  • program to swap two variables without using third variable in python

Python program to swap two numbers without third variable

The python program to swap two numbers without third variable 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))

a = a + b
b = a - b
a = a - b

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

The output of python program to swap two numbers without using third variable 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. Firstly, we take two user input. 

2. Then we perform a special mathematical trick to interchange the values of the variables of the two numbers.

3. We use here the .format() method to replace the braces with the values passed to the format function as an argument.

 

Snapshot for write a python program to swap two variables without using a third variable:

write a python program to swap two variables without using a third variable

 


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 08,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!