» Quick Introduction to Python » 3. Advanced » 3.3 Recursion

Recursion

If you want to understand recursion, you need to understand recursion first ...

In computer science, recursion is a method of solving a computational problem where the solution depends on solutions to smaller instances of the same problem.

Classic Fibonacci

def fibonacci(n):
    if n <= 1: # Stop here, you cannot recur forever
        return n
    else:
        # Call func itself, but with a smaller argument
        return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(1)) # 1
print(fibonacci(10)) # 55
print(fibonacci(20)) # 6765

Classic Factorial

def factorial(n):
    if n == 1 or n == 0:
        return 1
    else:
        return n * factorial(n-1)

print(factorial(1)) # 1
print(factorial(6)) # 720
print(factorial(10)) # 3628800

Code Challenge

Try to modify the code provided in the editor to sum the digits of a given number.

Loading...
> code result goes here
Prev
Next