0

I am doing the exercises in How to Think Like a Computer Scientist, and I couldn't get the answer to exercise number 11 in Chapter 11.

I am supposed to find why this code isn't working.

def swap(x,y):
    print("before swap statement: x:", x, "y:", y)
    (x,y) = (y,x)
    print("after swap statement: x:", x, "y:", y)

a = ["This", "is", "fun"]
b = [2,3,4]
print ("before swap function call: a:", a, "b:", b)
swap(a,b)
print("after swap function call: a:", a, "b:",b)

the result of this code is

('before swap function call: a:', ['This', 'is', 'fun'], 'b:', [2, 3, 4])
('before swap statement: x:', ['This', 'is', 'fun'], 'y:', [2, 3, 4])
('after swap statement: x:', [2, 3, 4], 'y:', ['This', 'is', 'fun'])
('after swap function call: a:', ['This', 'is', 'fun'], 'b:', [2, 3, 4])

swap(a, b) takes a, b and does (a, b) = (b, a), so I'm curious as to why this doesn't work. Can someone give me an explanation or an answer?

Kim SW
  • 19
  • 1
  • Briefly: when you reassign in the function, those become local variables. You didn't change the global variables `a` and `b`. – TigerhawkT3 Dec 28 '15 at 14:26
  • You could start reading about variable [scopes](http://python-textbok.readthedocs.org/en/latest/Variables_and_Scope.html) – Mr. E Dec 28 '15 at 14:27
  • 3
    This isn't the cause of your problem, but it looks like the tutorial you're using is for Python 3 (because it uses parentheses for `print`), and the interpreter you're using is Python 2 (because when you use `print` with parentheses, the output has parentheses). For this exercise there are only cosmetic differences between the versions, but it may cause you some more serious headaches in later exercises (for instance, ones that use `input`). Consider changing your tutorial or your interpreter so they use the same version. – Kevin Dec 28 '15 at 14:30

0 Answers0