I can't understand what the author means in this passage of "How to think like a computer scientist":
"Functions can return tuples as return values. For example, we could write a function that swaps two parameters:
def swap(x, y):
return y, x
Then we can assign the return value to a tuple with two variables:
a, b = swap(a, b)
In this case, there is no great advantage in making swap a function. In fact, there is a danger in trying to encapsulate swap, which is the following tempting mistake:
def swap(x, y): # incorrect version
x, y = y, x
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
If we call this function like this:
then a and x are aliases for the same value. Changing x inside swap makes x refer to a different value, but it has no effect on a in __main__. Similarly, changing y has no effect on b.
This function runs without producing an error message, but it doesn't do what we intended. This is an example of a semantic error."
When I run the following code:
x,y = y,x
a,b = swap(a,b)
a becomes 2 and b becomes 1
Can anyone explain what the author is trying to say plz?
the second - incorrect version - does not have a return statement which although it may look like it swaps x and y, it only affects variables local to the function and does not actually swap x and y in __main__.