Python Programs | IT Developer
IT Developer

Python Programs



Share with a Friend

Swap variables without using a third variable - Python Program

# Input values in two variables a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) print(f"Before swapping: a = {a}, b = {b}") # Swap using simultaneous assignment a, b = b, a print(f"After swapping: a = {a}, b = {b}")

Output

 
OUTPUT  :
Enter the first number: 10
Enter the second number: 20
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10

  • Right-hand side evaluation:

Python first evaluates the expressions on the right-hand side of the assignment (b, a). This creates a temporary tuple containing the current values of b and a.

  • Assignment:

The elements of this temporary tuple are then assigned to the variables on the left-hand side (a, b) in the corresponding order. This effectively swaps the values.