Exercise 6.3
← Previous Module 6: Functions Next →
Statement
Solution

Python Exercise 6.3: Recursive Factorial

Calculate factorial using recursion (function calling itself).

Your program should:

  • Define a recursive function factorial(n).
  • Base case: if n == 0 or n == 1, return 1.
  • Recursive case: return n * factorial(n-1).
  • Test with user input.

Sample Interaction:

Input
Output
5
120

Solution

Here is the recursive factorial function.

def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n - 1) # Test the function n = int(input("Enter n: ")) print(factorial(n))

Key Concepts:

  • Recursion calls the function itself.
  • Base case prevents infinite recursion.
  • Recursive case breaks down the problem.
Python 3
Test Console
Run code to see output...

Go Beyond Learning. Get Job-Ready.

Build in-demand skills for today's jobs with free expert-led courses and practical AI tools.

Explore All Courses
Scroll to Top