Python coding practice

Implement factorial(n)

Write the body of a recursive Python function that computes n factorial (written n!). Your code runs directly in the browser — no Python installation required.

The problem

The factorial of a non-negative integer n is the product of all positive integers from 1 up to n. By convention, 0! = 1.

0! = 1
1! = 1
4! = 4 × 3 × 2 × 1 = 24
6! = 6 × 5 × 4 × 3 × 2 × 1 = 720

Your function must pass these tests:

  • factorial(0)1
  • factorial(1)1
  • factorial(4)24
  • factorial(6)720
  • factorial(7)5040

Write your solution below, then click Run Tests:

Advertisement

Hints

Hint 1 — Identify the base case

The base case is already given: when n == 0, return 1. Every recursive call must move closer to this point by reducing n.

Hint 2 — Express the recursive relationship

Notice that n! = n × (n-1)!. In code that becomes one return statement: multiply n by the result of calling factorial with n - 1.

Hint 3 — Full solution
def factorial(n):
    if n == 0:
        return 1
    return n * factorial(n - 1)

The call chain for factorial(4): 4 × 3 × 2 × 1 × 1 = 24.

More coding problems