Turtle Recursion

To get a visual idea of recursion, Python's turtle graphics can be used to display graphics on screen. In the following example, the drawSpiral function takes a turtle t and a line_length and uses that turtle to draw a line of that length and turn right. Then the function calls itself recursively with a slightly smaller line, and the process continues until the "base case"--a line of length 0 or less--is reached.

#!/usr/bin/env python3
"""
recursive_spiral.py
Draws a spiral on the screen using recursion.
"""

from turtle import *

tom = Turtle()
win = Screen()

def drawSpiral(t, line_length):
    # base case
    if line_length <=0:
        return
    else:
        t.forward(line_length)
        t.right(90)
        drawSpiral(t, line_length - 5)      # recursive call

drawSpiral(tom, 100)
win.exitonclick()