Articles

Program to swap two variables in python using assignment operator

Program to swap two variables in python using assignment operator


In this python programming guide, we are going to learn:

  • python program to swap 2 variables assignment operation

Python program to swap 2 variables using assignment operator

The python program to swap two numbers using assignment operator 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, b = b, a

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

The output of python program to swap two numbers using assignment operator 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

Please check our video tutorial on program to swap two variables in python:

 

 

Few important tips about this program

1. Python provides this special double assignment functionality which helps us to directly swap two numbers at ease.

2. The double assginment thing is : a,b = b,a. This interchanges the value between a and b.

 

program to swap two variables in python using double assignment snapshot:

python program to swap two numbers

 


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 & Blockchain Enthusiast
Page Views :    Published Date : May 03,2023  
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!