<p>令人困惑的输出是因为<code>After for 0</code>输出来自函数的不同递归调用(与它上面的<code>Before for 0</code>输出不同)</p>
<p>以下是函数的一个版本,其中包含一些用于跟踪递归调用深度的额外信息:</p>
<pre><code>def findversion(aNode, aList, aFlag, i=1):
print "FindVersion ", aNode[0:1], 'call:', i
print "Findversion ", aFlag, 'call:', i
if aNode[1].find('Software') != -1:
aFlag = 1
aList.append(aNode[1])
if aFlag == 1 and aNode[0] == 'b':
aList.append(aNode[1])
print "Before for ", aFlag, 'call:', i
for elem in aNode[2:]:
print "After for ", aFlag, 'call:', i
findversion(elem,aList,aFlag,i+1)
</code></pre>
<p>这是新的输出,它显示了我所说的:</p>
<pre><code>FindVersion ['tr'] call: 1
Findversion 0 call: 1
Before for 0 call: 1
After for 0 call: 1
FindVersion ['td'] call: 2
Findversion 0 call: 2
Before for 1 call: 2 # this is from the recursive call
After for 0 call: 1 # this is from the original call
FindVersion ['td'] call: 2
Findversion 0 call: 2
Before for 0 call: 2
After for 0 call: 2
FindVersion ['b'] call: 3
Findversion 0 call: 3
Before for 0 call: 3
Main ['Software version']
</code></pre>