Python program to Swap Two Numbers
Here you will learn an example code of python program to swap two numbers with and without using third variable in python programming.
Python program to swap two numbers using third variable
1 2 3 4 5 6 7 8 9 | x = input('Enter value of x: ') y = input('Enter value of y: ') temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) |
Output
Enter value of x: 4
Enter value of y: 5
The value of x after swapping: 5
The value of y after swapping: 4
Python program to swap two numbers without third variable
1 2 3 4 5 6 7 8 | x = input('Enter value of x: ') y = input('Enter value of y: ') x = x + y y = x - y x = x - y print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) |
Output
Enter value of x: 10
Enter value of y: 20
The value of x after swapping: 20
The value of y after swapping: 10
Check out our other Python examples