Python Tutorial - Factorial function explained
Part 1: The Factorial Function
Let's start with writing a function to calculate the factorial of a number
The Factorial of a whole number greater than 1 is the product of all whole numbers from 1 to itself (1 and itself included). The '!' sign is used to denote factorial notation.
1! = 1
2! = 1 * 2 = 2
3! = 1 * 2 * 3 = 6
and so on
So our factorial function needs to accept a positive integer as input and calculate the product of all positive integers from one to that number.
We can do this is many ways
a) using a for loop in inside the function
b) using recursion
This is cleaner and shorter code, however when you run this, the interpreter throws a Recursion error:
return n * recursive_factorial(n-1)
[Previous line repeated 996 more times]
RecursionError: maximum recursion depth exceeded
The function goes into an endless loop, since the lower limit for n-1 is not defined and you can keep on subtracting 1 from an integer till negative infinity.
Let's set some constraints in our recursive_factorial function:
return 1 rather than '0' in the else statement, so that the product till the statement is triggered remains unchanged (anything multiplied by 1 is itself, but anything multiplied by 0, is 0).
Now let's add code for accepting the number for which you want to determine the factorial as input
Since python treats any input as string type, we need to convert the input to integer type before using in the function.