Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Implement a simple recursive function with a base case

Implement recursion with a clear base case by writing a factorial function.

Python practice17 minFunctions & ScopeIntermediateLast updated March 17, 2026

Problem statement

Implement factorial(n) that returns n! (n factorial) for non-negative integers using recursion. The base case is n == 0 which returns 1. Validate input: n must be an integer and non-negative; raise TypeError for non-integers and ValueError for negative integers. Use recursion for the general case.

Task

Write a recursive factorial(n) function that handles base cases and validates input.

Examples

Factorial of 4

Input

factorial(4)

Output

24

4! = 4 * 3 * 2 * 1 = 24; recursion reduces n until base case 0.

Input format

A single integer n passed to factorial(n).

Output format

Return an integer equal to n!. The returned value will be converted to a string for comparison.

Constraints

Use recursion with a base case n == 0. Validate that n is a non-negative integer.

Samples

Sample 1

Input

factorial(5)

Output

120

5! = 120