""" Exercise 3.25 from "A primer on..." We made two alternative implementations of the factorial function: - fact_loop; uses a for-loop, as suggested in the exercise - fact; performs the same task using recursion, where the function calls itself repeatedly """ def fact_loop(n): """This version uses a loop""" if n <= 1: #special cases; 0! = 1! = 1 return 1 else: #n>=2, use a for-loop to compute 2*3*...*n: product = 1 for i in range(2, n+1): #loop from 2 up to and including n product = product * i return product """ The function below uses recursion to perform the same task. Recursion is when a function calls itself. In the implementation below, for any n>1 the function will repeatedly call itself, each time with the argument reduced by 1, until the argument (n) is equal to 1. Then the function simply returns 1, because of the first if-test. The result is the product n * (n-1) * (n-2) ... * 1, which is the factorial. """ def fact(n): """Alternative version, using recursion""" #this print statement is useful to see what is happening: print(f"Calling factorial, n = {n}") if n <= 1: return 1 else: return n * fact(n - 1) # the function calls itself with a new argument (n-1) n = 4 print(f"{n}! = {fact(4)}, computed using recursion") """ Terminal> python fact.py Calling factorial, n = 4 Calling factorial, n = 3 Calling factorial, n = 2 Calling factorial, n = 1 4! = 24, computed using recursion """