Editor

Factorial

Loops · Intermediate · 65 XP · about 6 min

Write a function called factorial(n) that calculates the factorial of a non-negative integer n.

The factorial of n (written as n!) is the product of all positive integers from 1 to n: - 5! = 5 × 4 × 3 × 2 × 1 = 120 - 0! = 1 (by definition)

Example

factorial(5)   # Returns 120
factorial(0)   # Returns 1
factorial(1)   # Returns 1
factorial(10)  # Returns 3628800

Requirements

  • Handle n = 0 (returns 1)
  • You can assume n is non-negative
  • Use a loop (not recursion)
def factorial(n):
# Your code here
pass
# Test your function
print(factorial(5))
print(factorial(0))

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.