Calculate the Factorial of a Positive Integer
Quick Overview
Recursion mirrors the mathematical definition but stacks a frame per call, hitting Python's default limit near 1000. `math.factorial()` is iterative in C and has no such ceiling.
Deep Dive
1. The Challenge: Calculating Factorials
Create a function factorial(num) that takes an integer and returns its factorial (num!). For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.
2. Why It Matters
Factorials are fundamental in combinatorics, probability, permutations, and algorithm analysis.
3. The Python Solution
You can solve factorials using recursion, a loop, or the built-in math.factorial() module:
# Recursive Approach
def factorial(num):
if num <= 1:
return 1
return num * factorial(num - 1)
# Testing our function
print(factorial(3)) # Output: 6
print(factorial(5)) # Output: 120
print(factorial(1)) # Output: 1
print(factorial(0)) # Output: 1
4. Built-in Math Module
Python includes a built-in math.factorial():
import math
print(math.factorial(5)) # Output: 120
5. Common Mistakes
- Base Case Missing in Recursion: Forgetting
if num <= 1: return 1causes infinite recursion until Python raisesRecursionError: maximum recursion depth exceeded. - Handling 0!: By mathematical definition,
0! = 1. Ensure your base case returns1for zero.
6. Next Steps
Include base cases in recursive functions. Next, let's check if a list includes a specific element!
Next Up in Python Beginner Practice & Core Problem Solving
Return the Sum of Two Numbers
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
Convert Minutes into Seconds
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
Calculate the Area of a Triangle
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.