I'm a newbie taking Udacity's Intro to Computer Science course. We had a fairly simple question on our quiz about swapping values and I don't quite understand it. Here is the question:
Which of the following sequence of statements leaves the value of variable X the same as it was before the statements. Assume that both a and x refer to the integer values before this code.
Why is this true?
a,x = x,a
a,x = x,a
a,x = 4,5
a,x = 5, 4
It's simply swapping, then swapping again.
>>> a = 2 >>> x = 1 >>> a,x = x,a # We swapped them, so a = 1 and x = 2 now # During evaluation, this statement will be equivalent to "a,x = 1,2" >>> a,x = x,a # And now we swap them again, so they're back to their original values # During evaluation, this statement will be equivalent to "a,x = 2,1" >>> a 2 >>> x 1
What it seems you're missing is that the values change in the middle. You can't go through at the beginning and replace all occurrences of
a with 4 and 5 in your example because
a change in the middle of the operation.