Python Program to Swap Two Variables
A variable in Python is a symbolic name that is a reference or pointer to an object12. An object is anything that can be stored in memory, such as a number, a string, a list, etc. A variable is used to denote an object by that name1. For example, x = 5 means that the variable x refers to an integer object with the value 5. You can use x to access or manipulate that object2. In Python, you do not need to declare variables before using them or declare their type34. A variable is created when you first assign a value to it34. A variable can also change its reference to another object of any type after it has been created4. For example, y = “John” means that the variable y refers to a string object with the value “John”. You can later assign y to another object of any type, such as y = True.
Python Code :
The below Python program swaps two variables:
# Get input values from user a = input("Enter the value of a: ") b = input("Enter the value of b: ") # Print the original values print("Before swapping:") print("a =", a) print("b =", b) # Swap the values using a temporary variable temp = a a = b b = temp # Print the swapped values print("After swapping:") print("a =", a) print("b =", b)
In this program, the user is prompted to enter the values of two variables a and b. The values are then printed out.
To swap the values, the program uses a temporary variable temp to store the value of a. Then, the value of a is assigned to b and the value of temp (which is the original value of a) is assigned to a. This effectively swaps the values of a and b.
Finally, the program prints out the swapped values of a and b.
Output with a = 10 , b = 25 :
Before swapping: a = 10 b = 25 After swapping: a = 25 b = 10