Python Program to Swap Two Numbers Without Third Variable

Python programs to swap two numbers without using third variable have been shown here. The algorithm, pseudocode and time complexity of the programs have been covered here. Check here the flowchart of the programs.






1. Python Program & output to Swap Two Numbers Without Third Variable (Using Addition and Subtraction)

Code has been copied
# *************************************************
#           alphabetacoder.com
# Python program to swap two numbers without third
# variable but using arithmetic operators + and -
# *************************************************

# take input of two numbers
num1, num2 = map(int, input("Enter two numbers = ").split())

print("Before swapping: number1 =", num1, " and number2 =", num2)

# do swapping using + and -
num1 = num1 + num2
num2 = num1 - num2
num1 = num1 - num2

print("After swapping: number1 =", int(num1), " and number2 =", int(num2))

Output


Enter two numbers = 7 17

Before swapping: number1 = 7 and number2 = 17

After swapping: number1 = 17 and number2 = 7




2. Python Program & output to Swap Two Numbers Without Third Variable (Using Multiplication and Division)

Code has been copied
# *************************************************
#           alphabetacoder.com
# Python program to swap two numbers without third
# variable but using arithmetic operators * and /
# *************************************************

# take input of two numbers
num1, num2 = map(int, input("Enter two numbers = ").split())

print("Before swapping: number1 =", num1, " and number2 =", num2)

# do swapping using * and /
num1 = num1 * num2
num2 = num1 / num2
num1 = num1 / num2

print("After swapping: number1 =", int(num1), " and number2 =", int(num2))

Output


Enter two numbers = 7 17

Before swapping: number1 = 7 and number2 = 17

After swapping: number1 = 17 and number2 = 7