Swap Two Numbers in Python with Code

At some point in our lives, we think about how amazing it would be to wake up as someone else. You can admire as well as idolize that person in life. This idea of swapping personalities often fascinates us. While swapping personalities is not possible now, swapping numbers is quite easy.

Blogging Illustration

Swap Two Numbers in Python with Code

image

Option 1: Python Program to Swap Two Variables Using a Temporary Variable

Program code :

                    # The following code swaps two numbers

                    # Taking user input
                    num1 = int(input("Enter first number: "))
                    num2 = int(input("Enter second number: "))

                    # Printing before swap
                    print(f"Before swap: num1 = {num1} num2 = {num2}")

                    # Swapping
                    temp = num1
                    num1 = num2
                    num2 = temp

                    # Printing after swap
                    print(f"After swap: num1 = {num1} num2 = {num2}")

                    Output : 

                    Enter first number: 2 
                    Enter second number: 6 
                    Before swap: num1 = 2 num2 = 6
                    After swap: num1 = 6 num2 = 2

                        

Explanation of code :

  • Variables called num1 and num2 will take user inputs and just store those numbers.
  • Print statements will help in printing numbers just before and after the swapping.
  • A variable temp is used that will temporarily store num1 so that it will not be lost later while updating.
  • Later, we will update num1 with the value that is stored in num2.
  • Finally, num2 will be updated with temp.
  • In this way, we will swap both the numbers.

Option 2: Python Program to Swap Two Variables Without using a temporary variable

Program code :

                    # The following code swaps two numbers

                    # Taking user input
                    num1 = int(input("Enter first number: "))
                    num2 = int(input("Enter second number: "))

                    # Printing before swap
                    print(f"Before swap: num1 = {num1} num2 = {num2}")

                    # Swapping
                    num1, num2 = num2, num1

                    # Printing after swap
                    print(f"After swap: num1 = {num1} num2 = {num2}")


                    Output : 

                    Enter first number: 2 
                    Enter second number: 6 
                    Before swap: num1 = 2 num2 = 6
                    After swap: num1 = 6 num2 = 2

                        

Explanation of code :

  • Variables num1 and num2 will take user inputs and also store the numbers.
  • Print numbers will just print numbers before and after swapping.
  • Swapping is done without a temporary variable
  • Python will support the above syntax for swapping numbers.

Option 3: Python Program to Swap Two Variables Using Addition and Subtraction

Program code :

                        # The following code swaps two numbers


                        # Taking user input
                        num1 = int(input("Enter first number: "))
                        num2 = int(input("Enter second number: "))

                        # Printing before swap
                        print(f"Before swap: num1 = {num1} num2 = {num2}")

                        # Swapping
                        num1 = num1 + num2
                        num2 = num1 - num2
                        num1 = num1 - num2

                        # Printing after swap
                        print(f"After swap: num1 = {num1} num2 = {num2}")

                        Output : 

                        Enter first number: 2 
                        Enter second number: 6 
                        Before swap: num1 = 2 num2 = 6
                        After swap: num1 = 6 num2 = 

                        

Explanation of code :

  • Variables num1 and num2 will. Take user input and just store the numbers.
  • The print statement will help in printing numbers before and after the swap.
  • Swapping is done without using a temporary variable and also using a plus-minus operator.

Let’s swap 2 and 6 pictorially:

num1 = 2, num2 = 6

num1 = num1 + num2 = 2 + 6 = 8

num2 = num1 - num2 = 8 - 6 = 2

num1 = num1 - num2 = 8 - 2 = 6

Hence swapped

Option 4: Python Program to Swap Two Variables Using Multiplication and Division

Program code :

                            # The following code swaps two numbers

                        # Taking user input
                        num1 = int(input("Enter first number: "))
                        num2 = int(input("Enter second number: "))

                        # Printing before swap
                        print(f"Before swap: num1 = {num1} num2 = {num2}")

                        # Swapping
                        num1 = num1 * num2
                        num2 = num1 / num2
                        num1 = num1 / num2

                        # Printing after swap
                        print(f"After swap: num1 = {num1} num2 = {num2}")

                        Output :

                        Enter first number: 2 
                        Enter second number: 6 
                        Before swap: num1 = 2 num2 = 6
                        After swap: num1 = 6 num2 = 2

                        

Explanation of code :

  • Variables num1 and num2 will take user input and also store the input.
  • The print statement will help in printing numbers before and after swapping.
  • Swapping is done without using a temporary variable, and also using multiplication and division operators.

Let’s swap 2 and 6 pictorially:

num1 = 2, num2 = 6

num1 = num1 * num2 = 2 * 6 = 12

num2 = num1 / num2 = 12 / 6 = 2

num1 = num1 / num2 = 12 / 2 = 6

Hence swapped

Option 5: Python Program to Swap Two Variables Using XOR Operator

Program code :

                            # The following code swaps two numbers

                        # Taking user input
                        num1 = int(input("Enter first number: "))
                        num2 = int(input("Enter second number: "))

                        # Printing before swap
                        print(f"Before swap: num1 = {num1} num2 = {num2}")

                        # Swapping
                        num1 = num1 ^ num2
                        num2 = num1 ^ num2
                        num1 = num1 ^ num2

                        # Printing after swap
                        print(f"After swap: num1 = {num1} num2 = {num2}")

                        Output : 

                        Enter first number: 2 
                        Enter second number: 6 
                        Before swap: num1 = 2 num2 = 6
                        After swap: num1 = 6 num2 = 2

                        

Explanation of code :

  • Variables num1 and num2 will take user input and also store the variables.
  • The print statement will help in printing numbers before and after swapping.
  • Swapping is done without using an XOR operator.
  • Xor, or exclusive, is a logical operator that outputs false(0) if the inputs are the same; else, it outputs true(1).

XOR Table :

ABXOR
000
011
101
110

Let’s swap 2 and 6 pictorially:

                        num1 = 2 (0010) , num2 = 6 (0110)

                        num1 = num1 ^ num2 = 2 ^ 6 = 4

                        0010

                        0110

                        —----

                        0100 = 4

                        num2 = num1 ^ num2 =  4 ^ 6 = 2

                        0100

                        0110

                        —----

                        0010 = 2

                        num1 = num1 ^ num2 = 4 ^ 2 = 6

                        0100

                        0010

                        —----

                        0110 = 6
                        

Hence swapped.

Option 6: Python Program to Swap Two Variables Using both bitwise and arithmetic operations

Program code :

                    # The following code swaps two numbers

                    # Taking user input
                    num1 = int(input("Enter first number: "))
                    num2 = int(input("Enter second number: "))

                    # Printing before swap
                    print(f"Before swap: num1 = {num1} num2 = {num2}")

                    # Swapping
                    num1 = (num1 & num2) + (num1 | num2) # equivalent to num1 + num2 
                    num2 = num1 + (~num2) + 1 # equivalent to num1 - num2 
                    num1 = num1 + (~num2) + 1 # equivalent to num1 - num2

                    # Printing after swap
                    print(f"After swap: num1 = {num1} num2 = {num2}")

                    Output : 

                    Enter first number: 2 
                    Enter second number: 6 
                    Before swap: num1 = 2 num2 = 6
                    After swap: num1 = 6 num2 = 2

                        

Explanation of code :

  • Variables num1 and num2 will take user input and also store the variables.
  • The print statement will help in printing numbers before and after swapping.
  • Swapping is done without using a temporary variable.
  • You can also use the bitwise and, or, and not operators

Below are the truth tables given for these operators :

AND operator :

ABAND
000
010
100
111

OR operator :

ABOR
000
011
101
111

NOT Operator :

InputNOT
01
10

Let’s swap 2 and 6 pictorially:

                        num1 = 2 (0010) , num2 = 6 (0110)

                        num1 = (num1 & num2) + (num1 | num2)  = 2 + 6 = 8

                        0010                        0010

                            & 0110                     |  0110

                        —----                       —-----

                        0010 = 2                 0110 = 6

                        num2 = num1 +  (~num2) + 1 =  8 + (-7) + 1 = 2

                        ~ 0110 = -7

                        num1 = num1 +  (~num2) + 1  = 8 + (-3) + 1 = 6

                        ~ 0010 = -3
                        

Hence swapped

Real-life scenarios

Scenario 1: Swapping seats between two passengers on a flight

Program code :

                        # Swapping the seats of two passengers

                        # Taking user input
                        seat1 = input("Enter seat number of Passenger 1: ")
                        seat2 = input("Enter seat number of Passenger 2: ")

                        # Printing before swap
                        print(f"\nBefore Swap: Passenger 1 = {seat1}, Passenger 2 = {seat2}")

                        # Swapping
                        seat1, seat2 = seat2, seat1

                        # Printing after swap
                        print(f"After Swap: Passenger 1 = {seat1}, Passenger 2 = {seat2}")

                        Output Sample :

                        Enter the seat number of Passenger 1: 12A
                        Enter the seat number of Passenger 2: 15B

                        Before Swap: Passenger 1 = 12A, Passenger 2 = 15B
                        After Swap: Passenger 1 = 15B, Passenger 2 = 12A
                        

Explanation of code :

  • This kind of program will help in simulating a real-life scenario where two passengers will just switch their seat locations.
  • They do this without using a temporary variable.
  • Tuple unpacking is used.

Scenario 2: Swapping roles in a team project

Program code :

                        # Swapping roles in a team

                        # Taking user input
                        member1 = input("Enter name of Member 1: ")
                        role1 = input(f"Enter {member1}'s role: ")

                        member2 = input("\nEnter name of Member 2: ")
                        role2 = input(f"Enter {member2}'s role: ")

                        # Printing roles before swap
                        print(f"\nBefore Swap:")
                        print(f"{member1} is a {role1}")
                        print(f"{member2} is a {role2}")

                        # Swapping roles
                        role1, role2 = role2, role1

                        # Printing roles after swap
                        print(f"\nAfter Swap:")
                        print(f"{member1} is now a {role1}")
                        print(f"{member2} is now a {role2}")

                        Output Sample : 

                        Enter the name of Member 1: Alice
                        Enter Alice's role: Desithere Enter name of Member 2: Bob
                        Enter Bob's role: Developer

                        Before Swap:
                        Alice is a Designer
                        Bob is a Developer

                        After Swap:
                        Alice is now a Developer
                        Bob is now a Designer

                        

Explanation of code :

  • This example just demonstrates how this swapping of logic can be used in human resources, like assigning or switching roles between employees.
  • This can also be seen for students in group projects.

Conclusion :

Swapping two numbers in Python can be done in multiple ways—using a temporary variable, arithmetic operations, tuple unpacking, bitwise XOR, or a mix of bitwise and arithmetic logic. Each method demonstrates Python’s flexibility and logical depth. Understanding these methods enhances problem-solving skills and builds a strong foundation in programming logic. Enroll in a Python programming course in Noida for better learning and the latest trends of industry trends. Keep updating yourself to get your dream job.

Placed Students

Our Clients

Partners

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses