Python: can't figure this out?


In Runtime
This prints:

# 1-Python is fun
# 2-Python is fun
# 3-Python is fun
# 4-Python is fun
# 5-Python is fun

I understand why it prints in reverse order but i'm confused of why it includes (# 5-Python is fun) since it seems to subtract 1 from 5 before it prints. The only thing I can think of is that once if finds num1 to be >= to 1 to be TRUE it goes strait to print then loops back up to subtract then test again, I remember reading about the "counterclockwise" motion in the "Think Python" book. :banghead:

def moose(num1, str1):
if num1 >= 1:
moose(num1-1, str1)
print "# %d-%s" % (num1, str1)

moose(5, "Python is fun")


Fully Optimized
You may want to look up a bit on recursion, since what's happening here appears to be a lack of understand on this concept rather than python in particular.

Note that whenever you call moose, assuming num1 is >=1, it first calls moose with a number 1 less than num1, and *then* prints out its value (without 1 being subtracted.) The key point is that it doesn't subtract 1 from num1 and then store it back in num1, it just subtracts it and passes it to the next moose method. Once that line is over (which due to recursion in this case involves all other numbers being printed out), it goes onto execute the "print" line with the current value of num1, which hasn't changed, so it prints out a 5.

Whatever you do, get out of your head that it somehow jumps to print and then back up again - pretty much all programming languages, including python, will follow a logical progression from line to line unless otherwise stated (for instance when you reach the end of a loop, a break statement, return statement or similar.) If you have to resort to thinking loops work backwards or something weird like that, you've probably not understood it properly ;)