Solution Review: Factorial of a Number
This lesson will explain the solution to the factorial exercise in the previous chapter lesson.
We'll cover the following...
Solution
Press + to interact
def factorial(n):# Cover base casesif n==0 or n==1:return 1if n < 1:return -1# multiply all postiive integers below nproduct = 1while(n > 1):product = product * nn = n-1return productprint(factorial(5))
Explanation
The function starts with handling the edge cases. We know that for n==0
and n==1
, we need to return 1
. Therefore, we write an if
statement with an or
in between the ...