This Python Recursion lesson is for a beginner. Read the short notes, run each example, then change one name or number and run it again.
A recursive function calls itself with a smaller problem. It needs a base case that stops the calls.
A loop is usually simpler for counting. Recursion fits a value that contains the same kind of value, such as a folder of folders.
Example 1: Start here
Without the n == 0 stop, the calls never end.
def countdown(n): # define the function; it runs when you call it
if n == 0: # run the indented lines only when this is true
return "Go" # send this value back to the caller
return str(n) + " " + countdown(n - 1) # send this value back to the caller
print(countdown(3))
Example 2: Countdown
Each call gets a smaller n. The call stops when n is 0.
def down(n): # define the function; it runs when you call it
if n == 0: # run the indented lines only when this is true
print("go")
return # send this value back to the caller
print(n)
down(n - 1) # call the function
down(3) # call the function
Example 3: A sum
add_up(4) is 4 + 3 + 2 + 1.
def add_up(n): # define the function; it runs when you call it
if n == 1: # run the indented lines only when this is true
return 1 # send this value back to the caller
return n + add_up(n - 1) # send this value back to the caller
print(add_up(4))
Example 4: The loop version
A loop is often clearer than recursion for a simple total.
total = 0 # a whole number
for n in range(1, 5): # repeat once per number; range stops before the last
total += n # update the stored value
print(total)
