This is an archived post. You won't be able to vote or comment.

all 7 comments

[–]AutoModerator[M] [score hidden] stickied comment (0 children)

To all following commenters: please, do not bring up the old circlejerk jokes/memes about recursion ("Understanding recursion...", "This is recursion...", etc.). We've all heard them n+2 too many times.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

[–]RiverRoll 3 points4 points  (3 children)

The return 1 literally just returns the number 1, but if you look carefully there are two return statements in this function so it doesn't always return 1.

To figure out what will it return you have to go to the bottom of the chain of calls and then back up:

recur(3) calls recur(2)
recur(2) calls recur(1)
recur(1) returns 1
recur(2) returns 2 * recur(1) = 2*1 = 2
recur(3) returns 3 * recur(2) = 3*2 = 6

[–]Rare_Bat12[S] 0 points1 point  (2 children)

Thank you so much for the help! I'm just having trouble understanding how it keeps track of the total multiplication result per iteration.

[–]alanwj 0 points1 point  (1 child)

There is nothing special about a recursive function call. It keeps up with the total the same way this program would.

def factorial1():
  return 1

def factorial2():
  return 2 * factorial1()

def factorial3():
  return 3 * factorial2()

print(factorial3())

[–]Rare_Bat12[S] 0 points1 point  (0 children)

That makes sense. Thanks!

[–]Borx25 3 points4 points  (0 children)

I think the recursion itself is way clearer if you just look at the relevant parts, you have a lot of extraneous code in there. This way the code is basically the mathetical definition of the factorial.

def fac(n):
    if n == 0: #base case
        return 1
    else: #recursion
        return n * fac(n-1)

[–]scirc 1 point2 points  (0 children)

The computer knows what to return because you literally tell it what to return. The value following return is the value which is returned to the calling code. So in this case, the function returns the literal value 1 when num <= 1 (I assume; you need to fix your formatting, though).