Python program to swap two variables

Python program to swap two variables

 

Python program to swap two variables, Python program to swap two variables without using a third variable.

 

Example 1:- In this example, we will swap the values of two variables with each other. We will use a third variable to temporarily store the value.
 

a=int(input(‘Enter any number: ‘))
b=int(input(‘Enter any other number: ‘))
print(‘before swapping the values are…..’)
print(‘a=’,a)
print(‘b=’,b)
temp=a
a=b
b=temp
print(‘after the swapping values are….’)
print(‘a=’,a)
print(‘b=’,b)

 
Output

Enter any number: 10
Enter any other number: 20
before swapping the values are…..
a= 10
b= 20
after the swapping values are….
a= 20
b= 10

 
Example 2:- Without using the third variable.
Python program to swap two variables without using a third variable.

a=int(input(‘Enter any number: ‘))
b=int(input(‘Enter any other number: ‘))
print(‘before swapping the values are…..’)
print(‘a=’,a)
print(‘b=’,b)
a=a+b
b=a-b
a=a-b
print(‘after the swapping values are….’)
print(‘a=’,a)
print(‘b=’,b)

 
Output

Enter any number: 5
Enter any other number: 9
before swapping the values are…..
a= 5
b= 9
after the swapping values are….
a= 9
b= 5

 

Or you can write a simple one-line code to swap the values of two variables.

a=int(input(‘Enter any number: ‘))
b=int(input(‘Enter any other number: ‘))
print(‘before swapping the values are…..’)
print(‘a=’,a)
print(‘b=’,b)
a,b = b,a
print(‘after the swapping values are….’)
print(‘a=’,a)
print(‘b=’,b)

Output

Enter any number: 20
Enter any other number: 11
before swapping the values are…..
a= 20
b= 11
after the swapping values are….
a= 11
b= 20

 
 
Share in a Single Click

Leave a Reply

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