Python program to exchange two numbers without using third number

Python program to exchange the values of two numbers without using a third number :

In this example, we will learn how to exchange two numbers without using any extra number. We all know to exchange two numbers using a temporary number. But how to achieve this without using a third number? Let’s have a look :

The algorithm to exchange two numbers without using the third number :

1. Get inputs of both numbers from the user. Store them in two different variables.
2. Add both numbers and store it in the first number variable.
3. Subtract the second number from the first number and store it in the second number variable.
4. Subtract again the second number from the first number ( the second number is changed to the first number in the third step above) and store it in the first number variable.
5. Now, both numbers are exchanged i.e. first number variable holds the second number and the second number variable holds the first number.

Python program :

```#1
first = int(input("Enter the value of the first number : "))
second = int(input("Enter the value of the second number : "))

#2
first = first + second

#3
second = first - second

#4
first = first - second

#5
print("After exchange, First number is : ",first," Second number is : ",second)
```

Explanation :

The commented numbers in the above program denotes the step number below :

1. Ask the user to enter the first and second number and store it in the variable first and second. For example, user entered 1 for first and 2 for second.
2. Add both first and second and assign the value to first. Now, first become 1 + 2 = 3
3. Subtract second from first and store it in second. Now second is 3 – 2 = 1 i.e. the initial value of first.
4. Subtract second from first and store it in first. first become 3 – 1 = 2 i.e. the initial value of second.
5. Print out the final values of first and second.

Examples :

```Enter the value of the first number : 12
Enter the value of the second number : 23
After exchange, First number is :  23  Second number is :  12

Enter the value of the first number : 1
Enter the value of the second number : 2
After exchange, First number is :  2  Second number is :  1

Enter the value of the first number : 100
Enter the value of the second number : 200
After exchange, First number is :  200  Second number is :  100
```