0
def f(x,b):
    global a
    print(x,a-b)
    a = 3
def g(a,b):
    f(b,a)
    print(a,b)
a = 1
b = 2
g(2,a)
print(a,b)

Hey guys so I am fairly new to Python and I have an exam soon. Our teacher requires us to trace code and he said that if we could trace this successfully we would be able to trace anything on the exam as this should be the highest level of difficulty. Can someone please tell me what this function will print and explain how you got there ok? Thank you.

1
  • 2
    Just pretend you are a Python interpreter, and execute it on a piece of paper one line at a time, keeping track of all variables and function calls. Commented Feb 21, 2017 at 6:48

1 Answer 1

2

Comments are labeled with their order of exeuction, read them in order of the number in the left

def f(x,b): #4. We get called with (1,2)
    global a #5. Any changes to a will be reflected globally
    print(x,a-b) #6. prints: 1, -1  (1-2)=-1
    a = 3 #change a=3 globally
def g(a,b): #2. this gets called once with g(2,1)
    f(b,a)  #3. so we call f with (1,2)
    print(a,b) #7. prints:(2,1)
a = 1
b = 2
g(2,a) #1. Go to g(a,b)
print(a,b) #8. A was changed to 3 in f(x,b), prints(3,2)

#final output in order:
#1,-1  (from #6)
#2,1   (from #7)
#3,2   (from #8)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.