In Python values of two variables can be easily swapped with each other. For example – If there is a variable x = 10 and other one y = 5 then swapping values of x, y variables with each other and making x = 5, y = 10 is super simple in Python Programming Language.
Below is Python Code for Swapping Two Variables
- Define two variables for example x = 10, y = 5
- Define a temporary variable temp and makes it equal to x using temp = x statement
- Now assign value of y to x using x = y statement
- Assign y value of temporary variable(temp) using y = temp statement
That’s it now value of x have become value of y and vice-versa.
# Swapping two variables in Python Programming Language
x = 10
y = 5
# Let's swap x and y values
temp = x
x = y
y = temp
# Printing out new swapped values of x, y
print("After swapping x is =>", x)
print("After swapping y is =>", y)
Output of Above Code
After swapping x is => 5
After swapping y is => 10
No Comments
Leave a comment Cancel