typestar

Recursion in Python

Functions that call themselves, shrinking toward a base case.

def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)


def count_down(n):
    if n == 0:
        return ["liftoff"]
    return [n] + count_down(n - 1)


def digits_sum(n):
    if n < 10:
        return n
    return n % 10 + digits_sum(n // 10)

How it works

  1. factorial multiplies down to the base case of 1.
  2. count_down builds a list on the way back up.
  3. digits_sum peels one digit per call with % and //.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
224
Tokens
76
Three-star pace
95 tpm

At the three-star pace of 95 tokens a minute, this run takes about 48 seconds.

Type this snippet

Step 5 of 6 in Functions, step 37 of 72 in Language basics.

← Previous Next →

Recursion in other languages