Python Program to Swap Two Numbers without using Third Variable

This is a Python Program to exchange the values of two numbers without using a temporary variable.

Problem Description

The program takes both the values from the user and swaps them without using temporary variable.

Problem Solution

1. Take the values of both the elements from the user.
2. Store the values in separate variables.
3. Add both the variables and store it in the first variable.
4. Subtract the second variable from the first and store it in the second variable.
5. Then, subtract the first variable from the second variable and store it in the first variable.
6. Print the swapped values.
7. Exit.

Program/Source Code

Here is source code of the Python Program to exchange the values of two numbers without using a temporary variable. The program output is also shown below.

 
a=int(input("Enter value of first variable: "))
b=int(input("Enter value of second variable: "))
a=a+b
b=a-b
a=a-b
print("a is:",a," b is:",b)
Program Explanation

1. User must first enter the values for both the elements.
2. The first element is assigned the sum of the first two elements.
3. Second element is assigned the difference between the sum in the first variable and the second variable, which is basically the first element.
4. Later the first element is assigned the difference between the sum in the variable and the second variable, which is the second element.
5. Then the swapped values are printed.

advertisement
advertisement
Runtime Test Cases
 
Case 1
Enter value of first variable: 3
Enter value of second variable: 5
a is: 5  b is: 3
 
Case 2
Enter value of first variable: 56
Enter value of second variable: 25
a is: 25  b is: 56

Sanfoundry Global Education & Learning Series – Python Programs.

To practice all Python programs, here is complete set of 150+ Python Problems and Solutions.

Note: Join free Sanfoundry classes at Telegram or Youtube

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.