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
factorialmultiplies down to the base case of 1.count_downbuilds a list on the way back up.digits_sumpeels one digit per call with%and//.
Keywords and builtins used here
count_downdefdigits_sumfactorialifreturn
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.
Step 5 of 6 in Functions, step 37 of 72 in Language basics.