Program to swap two variables in python

The following program shows to swap to variables by making a temporary variable. Two numbers are taken as input from the user. A temporary variable is created which stores the value for number1. ‘number1’ then stores the value of ‘number2’ and ‘number2’ stores the value of ‘temporary’. In this way the values of ‘number1’ and ‘number2’ got exchanged.

number1 = input('Enter your first number to swap: ')
number2 = input('Enter your second number to swap: ')

print("The value of the first number before swapping: ", number1)
print("The value of the second number before swapping: ", number2)

# Swapping of number is done by the use of a temporary variable
temporary = number1
number1 = number2
number2 = temporary

print("The value of first number after swapping with second number is: ", number1)
print("The value of second number after swapping with first number is: ", number2)

Output:

Enter your first number to swap: 15
Enter your second number to swap: 63
The value of the first number before swapping: 15
The value of the second number before swapping: 63
The value of first number after swapping with second number is: 63
The value of second number after swapping with first number is: 15

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments