Here's the recursive version of factorial:
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
And here's the iterative version:
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result
If I were explaining "factorial" to a high schooler, I'd say "multiply all the numbers from 1 up to n." That's what that loop version does.
The recursive version ("n times factorial of n-1") is neat, but it's not any clearer.
🧵 (2/6)