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)
嘿伙计们,所以我对Python很新,我很快就会参加考试。我们的老师要求我们跟踪代码,他说如果我们能够成功跟踪,我们就可以在考试中追踪任何内容,因为这应该是最高难度。有人可以告诉我这个功能会打印出来并解释你是如何到达那里的吗?谢谢。
答案 0 :(得分:2)
评论标有他们的执行顺序,按照左边的数字顺序读取
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)