Python Program to Swap Variables

Swap values using third variable

1# Python program to swap two variables 2a = 10 3b = 20 4 5temp = a 6a = b 7b = temp 8 9print("a:", a) 10print("b:", b)

Output

1a: 20 2b: 10

Swap Two Variables Without Using Third Variable

1a = 10 2b = 20 3 4# Use assignment operator to swap variable values 5a, b = b, a 6 7print("a:", a) 8print("b:", b)

Output

1a: 20 2b: 10

Using Arithimatic Operator to Swap Variables

1a = 10 2b = 20 3 4a = a + b 5b = a - b 6a = a - b 7 8print("a:", a) 9print("b:", b)

Output

1a: 20 2b: 10