B2.4.4–5 · HL recursion

Fractal tree · HL application

Python · step by step

Fractal tree · HL application

The same drawing rule repeats at a smaller scale until depth reaches zero.

Select Play or Next line to follow Python execution.

Python implementation

The highlight marks the next line to execute. Values show the state before that line.

import mathsegments = []def fractal(x, y, length, angle, depth):    if depth == 0:        return    end_x = x + length * math.cos(angle)    end_y = y - length * math.sin(angle)    segments.append([x, y, end_x, end_y])    fractal(end_x, end_y, length * 0.65, angle + 0.5, depth - 1)    fractal(end_x, end_y, length * 0.65, angle - 0.5, depth - 1)

B2.4.4 application: focus on self-similarity, smaller subproblems and the stopping condition. Branching code is illustrative, not a B2.4.5 tracing requirement. math is Python’s standard maths module; angles are in radians. segments records endpoints for the drawing. Every branch creates two smaller branches.

Keep exploring

Return to the recursion lesson →

All B2.4 animations →

All practice & resources →