Variable Swapping : Swapping two variables is possible through the mutual exchange of values of the variables. It is usually done by using a temporary variable. Swapping of two numbers is also possible without using a temporary variable, both the codes are given in this example.
Python program to swap two numbers using temporary variable
# Python Code for Swapping Two Variables # Read the input values as string, we are not converting string to int in this example. a = input ('Enter the value of a : ') b = input ('Enter the value of b : ') # print the values of a and b before swapping print('The value of a before swapping : ', a) print('The value of b before swapping : ', b) # create a temporary variable and swap the string values temp = a a = b b = temp # print the values of a and b after swapping print('The value of a after swapping : ', a) print('The value of b after swapping : ', b)
OUTPUT:
Enter the value of a : 181131 Enter the value of b : 81189 The value of a before swapping : 181131 The value of b before swapping : 81189 The value of a after swapping : 81189 The value of b after swapping : 181131
Python program to swap numbers without using temporary variable
# Python Code for Swapping Two Variables # Read the input values and convert string to int for calculations. a = int(input ('Enter the value of a : ')) b = int(input ('Enter the value of b : ')) # print the values of a and b before swapping print('The value of a before swapping : ', a) print('The value of b before swapping : ', b) # Swapping without temporary variable a=a+b b=a-b a=a-b # print the values of a and b after swapping print('The value of a after swapping : ', a) print('The value of b after swapping : ', b)
Output:
Enter the value of a : 181131 Enter the value of b : 81189 The value of a before swapping : 181131 The value of b before swapping : 81189 The value of a after swapping : 81189 The value of b after swapping : 181131
Swapping using Comma operator
a, b = b, a
Swapping using XOR
a = a ^ b b = a ^ b a = a ^ b