Factorial

Write a recursive function factorial(n) and print n! for the given n. Remember that 0! = 1.

What to build

A recursive function and a call to it.

Requirements

  • Write factorial(n) using recursion.
  • Make factorial(0) return 1.
  • Read n and print the result.

Input

One whole number n from 0 to 20.

Output

The value of n!.

Constraints

n is from 0 to 20.

Example

Input:

4

Output:

24

Why it works

Each call passes a smaller n, so the base case is always reached, and the results multiply on the way back.

Examples

Example 1 · Input
4
Expected output
24
Example 2 · Input
0
Expected output
1

Prompts inside input() are ignored when checking, so input("n: ") is fine.

Hints

Hint 1

Base case: if n <= 1, return 1.

Hint 2

Otherwise return n * factorial(n - 1).

Solution

Show one correct solution (try it yourself first)
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

n = int(input())
print(factorial(n))

Lesson: Functions and recursion →