The next challenge asks us to write a function that takes a number and returns the factorial of it. The text below is taken straight from Coderbyte:
Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24.
Thus, to solve this problem I have chosen a recursive solution. The only reason for choosing recursion is that it makes the solution shorter and more straightforward. A for loop can be used as well.
A recursive function such as FirstFactorial makes calls to itself a finite number of times until it reaches a base case. Thus, the solution starts by defining a base case test. If this test is not present, the function results in an error, because it will keep subtracting one from the num variable until it runs out of memory.
Therefore, the function keeps returning num multiplied by num – 1. For instance, if num is 3 the function returns 1! = 1, 2! = 1! * 2, 3 = 2! * 3.
def FirstFactorial(num): if num == 1: return 1 # multiply the number by the same number - 1 return num*FirstFactorial(num-1)
As mentioned above, the solution can be written using a for loop:
def FirstFactorial(num): factorialNumber = 1 for num in range(1, num+1): factorialNumber *= num return factorialNumber
The second solution makes it easier to understand what is happening behind the scenes.