Python Program to Swap Two Numbers

In this post, we will learn how to swap two numbers using Python Programming language.

We will swap two numbers using the following approaches:

  1. Using Temporary Variable
  2. Without Using Temporary Variable

So, without further ado, let’s begin this tutorial.

Python Program to Swap Two Numbers Using Temporary Variable

# Python Program to Swap Two Numbers Using Temporary Variable
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

print("Value of a before swapping: ", a)
print("Value of b before swapping: ", b)

# Swapping two numbers using temporary variable
temp = a;
a = b;
b = temp;

# Displaying output
print("Value of a after swapping: ", a)
print("Value of b after swapping: ", b)

Output

Enter the first number: 5
Enter the second number: 7
Value of a before swapping:  5
Value of b before swapping:  7
Value of a after swapping:  7
Value of b after swapping:  5

How Does This Program Work ?

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

The user is asked to enter two numbers.

print("Value of a before swapping: ", a)
print("Value of b before swapping: ", b)

Then, We display the value of both numbers before swapping.

temp = a;
a = b;
b = temp;

We store the value of a in temp variable. Then, we put the value of b in a variable and later the value of temp in b variable. In this way, the value of both the numbers get interchange.

# Displaying output
print("Value of a after swapping: ", a)
print("Value of b after swapping: ", b)

Finally, the result is displayed on the screen using print() function.

Python Program to Swap Two Numbers Without Using Temporary Variable

# Python Program to Swap Two Variables Without Using Temporary Variable
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))

print("Value of a before swapping: ", a)
print("Value of b before swapping: ", b)

# Swapping two numbers without using temporary variable
a, b = b, a

# Displaying output
print("Value of a after swapping: ", a)
print("Value of b after swapping: ", b)

Output

Enter the first number: 12
Enter the second number: 25
Value of a before swapping:  12
Value of b before swapping:  25
Value of a after swapping:  25
Value of b after swapping:  12

Conclusion

I hope after going through this post, you understand how to swap two numbers using Python Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

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