Python Program to Swap Two Variables


In this blog post,we are going to learn how to swap two variables by using a temporary variable and
swap two variables without using any temporary variable.

Python Program to Swap Two Variables Using temporary variable:-

# Python program to swap two variables Using temporary #variable or Third variable

# If you want to take input from the user then
# var1 = input('Enter value of x: ')
# var2 = input('Enter value of y: ')

var1 = 20
var2 = 40

# create a temporary variable and swap the values
var_temp = var1
var1 = var2
var2 = var_temp

print('The value of var1 after swapping: {}'.format(var1))
print('The value of var2 after swapping: {}'.format(var2))

Output:-

The value of x after swapping: 40
The value of y after swapping: 20

Python Program to Swap Two Variables without Using temporary or third variable:-

# Python program to swap two variables without Using #temporary  or Third variable

# If you want to take input from the user then
# var1 = input('Enter value of x: ')
# var2 = input('Enter value of y: ')

var1 = 20
var2 = 40

# create a temporary variable and swap the values
var1=var1+var2
var2 = var1-var2
var1 = var1-var2

print('The value of var1 after swapping: {}'.format(var1))
print('The value of var2 after swapping: {}'.format(var2))

output:-

The value of var1 after swapping: 40
The value of var2 after swapping: 20

 

https://bit.ly/2lgLuJ1 https://bit.ly/2lAbgYW https://bit.ly/2ngU8ry

Leave a Reply

Your email address will not be published. Required fields are marked *