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
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 – 1000 Python Programs.

If you wish to look at all Python Programming examples, go to 1000 Python Programs.

Free 30-Day Java Certification Bootcamp is Live. Join Now!

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
I’m Manish - Founder and CTO at Sanfoundry. I’ve been working in tech for over 25 years, with deep focus on Linux kernel, SAN technologies, Advanced C, Full Stack and Scalable website designs.

You can connect with me on LinkedIn, watch my Youtube Masterclasses, or join my Telegram tech discussions.

If you’re in your 40s–60s and exploring new directions in your career, I also offer mentoring. Learn more here.