Python program that swaps the values of two variables:

Created with Sketch.

Here is a Python program that swaps the values of two variables:

# Method 1: using a temporary variable
x = 5
y = 10
temp = x
x = y
y = temp
print("x =", x)
print("y =", y)

The program uses a temporary variable, “temp” to store the value of x, then assigns the value of y to x, and finally assigns the value of temp (original value of x) to y.

Another way to swap two variables is by using python tuple and unpacking features:

# Method 2: using tuple unpacking
x = 5
y = 10
x, y = y, x
print("x =", x)
print("y =", y)

This method is more concise, elegant and efficient. It creates a tuple of x, y and then unpack the values into x and y.

Both the methods will give you the same output which is x = 10, y = 5. You can use any method that suits your need or preference.

Leave a Reply

Your email address will not be published. Required fields are marked *