A fundamental task in programming is swapping the values of two variables. In Python, this can be easily accomplished through a simple and concise program. The act of swapping allows us to interchange the values stored in two variables, providing us with a flexible tool to manipulate data efficiently. By implementing a Python program to swap two numbers, we gain the ability to rearrange and reassign values effortlessly, thereby enabling us to solve a wide range of computational problems.
In this article, we will explore multiple solutions that harnesses the power and versatility of Python, demonstrating the language’s simplicity and effectiveness. Let’s dive into the world of Python programming and learn how to swap two numbers with ease.
01. Method
Using just simple mathematics operations (addition, subtraction).
def swapTwoNumber(a,b): a = a + b b = a - b a = a - b return [a,b] A = 40 B = 20 print("Before SwappingnValue Of A: ",A,"nValue Of B: ",B) A1,B1= swapTwoNumber(A,B) print("nAfter SwappingnValue Of A: ",A1,"nValue Of B: ",B1)
Output:
Before Swapping Value Of A: 40 Value Of B: 20 After Swapping Value Of A: 20 Value Of B: 40
02. Method
Using just Python programming syntax concept.
def swapTwoNumber(a,b): print("Before SwappingnValue Of A: ",a,"nValue Of B: ",b) a,b = b,a print("nAfter SwappingnValue Of A: ",a,"nValue Of B: ",b) A = 40 B = 20 swapTwoNumber(A,B)
Output:
Before Swapping Value Of A: 40 Value Of B: 20 After Swapping Value Of A: 20 Value Of B: 40
03. Method
Using XOR gate concept.
def swapTwoNumber(a,b): print("Before SwappingnValue Of A: ",a,"nValue Of B: ",b) a = a ^ b b = a ^ b a = a ^ b print("nAfter SwappingnValue Of A: ",a,"nValue Of B: ",b) A = 40 B = 20 swapTwoNumber(A,B)
Output:
Before Swapping Value Of A: 40 Value Of B: 20 After Swapping Value Of A: 20 Value Of B: 40
04. Method
Using third variable concept.
def swapTwoNumber(a,b): print("Before SwappingnValue Of A: ",a,"nValue Of B: ",b) c = a a = b b = c print("nAfter SwappingnValue Of A: ",a,"nValue Of B: ",b) A = 40 B = 20 swapTwoNumber(A,B)
Output:
Before Swapping Value Of A: 40 Value Of B: 20 After Swapping Value Of A: 20 Value Of B: 40
05. Method
Using division and multiplication method.
def swapTwoNumber(a,b): print("Before SwappingnValue Of A: ",a,"nValue Of B: ",b) a = a * b b = a / b a = a / b print("nAfter SwappingnValue Of A: ",a,"nValue Of B: ",b) A = 40 B = 20 swapTwoNumber(A,B)
Output:
Before Swapping Value Of A: 40 Value Of B: 20 After Swapping Value Of A: 20 Value Of B: 40