01Factorial
main.py
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))Output
120
Recursion in Python: solve problems by calling a function within itself, with factorial, Fibonacci, list sums, and power examples.
def factorial(n):
if n <= 1:
return 1
return n * factorial(n - 1)
print(factorial(5))120
def fib(n):
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
print([fib(i) for i in range(8)])[0, 1, 1, 2, 3, 5, 8, 13]
def sum_list(items):
if not items:
return 0
return items[0] + sum_list(items[1:])
print(sum_list([1, 2, 3, 4, 5]))15
def power(base, exp):
if exp == 0:
return 1
return base * power(base, exp - 1)
print(power(2, 8))256