Python Program to Swap Two Variables_py4u.tech

Python Program to Swap Two Variables

Python Program to Swap Two Variables

In this example, you will learn to swap two variables by using a temporary variable and, without using a temporary variable.

To understand this example, you should have knowledge of the following Python programming topics:

  • Python Data Types
  • Python Input, Output and Import
  • Python Operators

Python program to swap two variables using Temporary Variable

a=5

b=10
#swapping No With Temp Variable
temp=a
a=b
b=temp
print("After Swap a = ", a)
print("After Swap b = ", b)

Output:

After Swap a =  10 
After Swap b = 5

In this program, we use the temp variable to hold the value of x temporarily. We then put the value of y in x and later temp in y. In this way, the values get exchanged.

Python program to swap two variables without using Temporary Variable

In Python, there is a simple construct to swap variables.

a=5

b=10
# Swapping
a,b=b,a
print("After Swap a = ", a)
print("After Swap b = ", b)

Output:

After Swap a =  10

After Swap b = 5

If the variables are both numbers, we can use arithmetic operations to do the same. It might not look intuitive at first sight. But if you think about it, it is pretty easy to figure it out.

Python program to swap two variables using Addition and Subtraction

a=5

b=10
# Swapping
a=a+b
b=a-b
a=a-b
print("After Swap a = ", a)
print("After Swap b = ", b)

Output:

After Swap a =  10 
After Swap b = 5

Python program to swap two variables using Multiplication and Division

a=5 
b=10
# Swapping
a=a*b
b=a//b
a=a//b
print("After Swap a = ", a)
print("After Swap b = ", b)

Output:

After Swap a =  10

After Swap b = 5

Python program to swap two variables using XOR swap

Note : This algorithm works for integers only

a=5

b=10
# Swapping
a=a^b
b=a^b
a=a^b
print("After Swap a = ", a)
print("After Swap b = ", b)

Output:

After Swap a =  10

After Swap b = 5

Download Jupiter Notebook File – Github

More Topics:

Game with nos solution in python

Sort an array of 0s, 1s and 2s – geeksforgeeks

python solution Reading Files using Python

Keywords and Identifier in Python?

Introduction to Classes, Objects and Methods

techengers

Add comment

Leave a Reply

Follow us

Don't be shy, get in touch. We love meeting interesting people and making new friends.

Most popular