Swapping Variables
Swapping Variables#
One more quick exercise to test your understanding of variables.
You have two variables x and y. You want to swap their values so that the value of x is stored in y and the value of y is stored in x.
Here is some code I have written to do that. Will this code work? … Think about it before running the cell in Colab.
x = 5
y = 4
y = x
x = y
In the cell below try to print x and y:
Did we get the expected output y=5 and x=4? If not, why not.
Here is another attempt at doing this
x = 5
y = 4
temp_var = y
y = x
x = temp_var
Again, try printing x and y, is it correct now? Consider what happened here from the computer’s perspective? Do you understand why one method worked and the other didn’t? If not: Ask one of us!