In this article, we will show you, How to write a Python program to Swap Two Numbers using Temp variable, Bitwise Operators, and Arithmetic Operators

## Python Program to Swap Two Numbers

This python program to swap two numbers helps user to enter two numeric values. Next, it will swap those two values using temp variables

# Python Program to Swap Two Numbers a = float(input(" Please Enter the First Value a: ")) b = float(input(" Please Enter the Second Value b: ")) print("Before Swapping two Number: a = {0} and b = {1}".format(a, b)) temp = a a = b b = temp print("After Swapping two Number: a = {0} and b = {1}".format(a, b))

**OUTPUT**

**ANALYSIS**

In the above example, we assigned a = 10 and b = 20

Temp = a – assigning a value to Temp variable

Temp = 10

a = b – assign b value to variable a

a = 20

b = Temp – Temp value to variable b

b = 10

## Python Program to Swap Two Numbers using Functions

This program for swap numbers in python is same as above but this time we separated the logic using Functions

# Python Program to Swap Two Numbers def swap_numbers(a, b): temp = a a = b b = temp print("After Swapping two Number: num1 = {0} and num2 = {1}".format(a, b)) num1 = float(input(" Please Enter the First Value : ")) num2 = float(input(" Please Enter the Second Value : ")) print("Before Swapping two Number: num1 = {0} and num2 = {1}".format(num1, num2)) swap_numbers(num1, num2)

**OUTPUT **

## Python Program to Swap Two Numbers using Arithmetic Operators

In this program, instead of using temp or third variable to swap two numbers we are going to use Arithmetic Operators

# Python Program to Swap Two Numbers a = float(input(" Please Enter the First Value a: ")) b = float(input(" Please Enter the Second Value b: ")) print("Before Swapping two Number: a = {0} and b = {1}".format(a, b)) a = a + b b = a - b a = a - b print("After Swapping two Number: a = {0} and b = {1}".format(a, b))

**OUTPUT**

**ANALYSIS**

User Entered Values are a = 25 and b = 45

a = a + b

a = 25 + 45 = 70

b = a – b

b = 70 -45 = 25

a = a – b

a = 70 – 25 = 45

## Python Program to Swap Two Numbers using Bitwise Operator

In this program, we are using Bitwsie operators to swap two numbers

# Python Program to Swap Two Numbers a = int(input(" Please Enter the First Value a: ")) b = int(input(" Please Enter the Second Value b: ")) print("Before Swapping two Number: a = {0} and b = {1}".format(a, b)) a = a ^ b b = a ^ b a = a ^ b print("After Swapping two Number: a = {0} and b = {1}".format(a, b))

**OUTPUT**

Thank You for Visiting Our Blog