Type to search…
Skip to content

Recursion

A function that calls itself, and the base case that makes it stop.

Taught in
Llenguatges de marques i sistemes de gestió d’informacióDocuments dinàmicsASIXProgramacióProgramació estructuradaDAW-BIO

Introduction

In Iteració you learned to repeat a block as many times as needed.

With a while you can draw any polygon, any rosette and any spiral.

But there are figures that are not a repetition.

Look at a tree.

A tree is not a trunk repeated thirty times. It’s a trunk that opens into two branches, and each branch is a smaller tree.

This sentence —a branch is a smaller tree— you can’t write it with a loop.

You can write it with a function that calls itself.

A function that calls itself

Start with something you already know how to do.

In Iteració you drew the spiral with a while and an accumulator:

python
side = 5
while side < 150:
    forward(side)
    left(90)
    side += 5

Now write it without a loop.

One segment of the spiral is one segment, and then a smaller spiral:

python
def spiral(side):
    forward(side)
    left(90)
    spiral(side + 5)

Read the last line carefully.

spiral calls spiral. The function uses itself, and this is called recursion.

The base case

Run this program and it won’t draw anything:

python
from turtle import *

def spiral(side):
    forward(side)
    left(90)
    spiral(side + 5)


spiral(5)

Keep reading — it's free.

The rest of this page is open to anyone with a free account. Nothing is sold here and nothing is charged for: the account exists so we know who agreed to the terms, and so we can send you the newsletter if you want it.

Create a free account

You will be asked to accept the Terms · Privacy Policy