2017-02-21 124 views
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) 

嘿,大家好,我對Python很新,我很快就要參加考試。我們的老師要求我們跟蹤代碼,他說如果我們能夠成功地追蹤這個問題,我們就能夠在考試中追蹤任何事情,因爲這應該是最高級別的難度。有人可以告訴我這個功能將打印和解釋你如何到那裏好嗎?謝謝。Python中的跟蹤代碼

+2

只是假裝你是一個Python解釋器,並在同一時間執行它在一張紙上一行,跟蹤所有變量和函數調用。 – DyZ

回答

2

評論都標有其exeuction的順序,讀他們的編號順序在左側

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)