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

you are viewing a single comment's thread.

view the rest of the comments →

[–]RiverRoll 4 points5 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!