Computer Forums Python: can't figure this out?

 05-11-2013, 11:15 AM #1 Baseband Member     Join Date: Jan 2013 Location: United States Posts: 81 Python: can't figure this out? 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. def moose(num1, str1): if num1 >= 1: moose(num1-1, str1) print "# %d-%s" % (num1, str1) else: return moose(5, "Python is fun") __________________ __________________
 05-12-2013, 02:52 PM #2 Site Team     Join Date: Jul 2009 Location: England, UK Posts: 3,434 Re: Python: can't figure this out? 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 __________________ __________________ Save the whales, feed the hungry, free the mallocs.
 05-12-2013, 02:56 PM #3 Baseband Member     Join Date: Jan 2013 Location: United States Posts: 81 Re: Python: can't figure this out? Thank you! __________________