Python Program to Swap Two Numbers without Using a Temp Variable

In this sample program, you will learn to swap two numbers without using a temporary variable and show the result using the print() function.

To understand this demo program, you should have the basic Python programming knowledge:

In the sample below, we are taking inputs from the user and store them in two different variables.

To swap them without a temp variable, we need to add both numbers and store the result in the first one.

Next, we’ve to subtract the second variable from the first one and save the result to the second one.

Finally, we’ll use the first variable to subtract from the second and also to store the result of this operation.

At this point, both the variables have swapped their values. We’ll now print the result.

Sample Code: Swap Two Numbers Without Using a Temp Variable

# This program swaps two numbers

int1 = int(input("Enter first number: "))
int2 = int(input("Enter second number: "))

print('Old value of int1 is {0} and int2 is {1}'.format(int1, int2))

int1 = int1 + int2
int2 = int1 - int2
int1 = int1 - int2

# Display the result
print('New value of int1 is {0} and int2 is {1}'.format(int1, int2))

The output of the above code is as follows:

Enter first number:  11
Enter second number:  22
Old value of int1 is 11 and int2 is 22
New value of int1 is 22 and int2 is 11

Now, try executing the above Python program yourself.