Learn how to compute mathematical factorials in Python using recursive functions and math.factorial().
Learn how to convert minutes into seconds in Python using arithmetic multiplication and basic unit conversions.
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!