user7596956
user7596956

Reputation: 7

Tracing Code in Python

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.

Upvotes: 0

Views: 212

Answers (1)

Keatinge
Keatinge

Reputation: 4321

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)

Upvotes: 2

Related Questions