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.
Create a function factorial(num) that takes an integer and returns its factorial (num!). For example, 5! = 5 * 4 * 3 * 2 * 1 = 120.
Factorials are fundamental in combinatorics, probability, permutations, and algorithm analysis.
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
Python includes a built-in math.factorial():
import math
print(math.factorial(5)) # Output: 120
if num <= 1: return 1 causes infinite recursion until Python raises RecursionError: maximum recursion depth exceeded.0! = 1. Ensure your base case returns 1 for zero.Include base cases in recursive functions. Next, let's check if a list includes a specific element!
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.
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.
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.