Search⌘ K
AI Features

Solution Review: Factorial of a Number

Explore how to implement a factorial function in Python by handling edge cases and using loops and conditionals. This lesson helps you build foundational skills in Python syntax useful for data science tasks.

We'll cover the following...

Solution

Python 3.5
def factorial(n):
# Cover base cases
if n==0 or n==1:
return 1
if n < 1:
return -1
# multiply all postiive integers below n
product = 1
while(n > 1):
product = product * n
n = n-1
return product
print(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 ...