Why does this recursive function not print done twice?
I'm still trying to understand recursion and what I expected the code to
print and what actually printed is different.
so here's the code which is just based off a simple example I found on
youtube,
def count(n):
if n > 0:
print "Count 1", ", ", n
count(n - 1)
print "Count 2", ", ", n
else:
print "Done"
count(1)
and this is what it prints,
Count 1 , 1
Done
Count 2 , 1
What I expected was
Count 1 , 1
Done
Done
My understanding (which of course is wrong) is that count(1) (for the
outer count function) will be called and because 1 is greater than 0 will
print 1, then count(1 - 1) (inner count function) will call count(0)
(outer count function) and since 0 is not greater than 1 this will print
Done. Then I thought the return from count(1 - 1) (inner count function)
would also return Done and since there were no other n values entered into
the inner count() that would be it. I'm not understanding how done prints
once and 1 prints twice???
No comments:
Post a Comment