Functions Jump to this section

Functions let you package a set of instructions once and call them many times. Functions make code cleaner and reusable.

Define and call a function Jump to this section

Use the def keyword to create a function.

import turtle

def square(t, size):
    for _ in range(4):
        t.forward(size)
        t.left(90)

t = turtle.Turtle()
square(t, 80)
square(t, 40)

square is a function that draws a square using the given turtle and size.

By adding (t, size) when creating the function, you can pass in values to be used by the function.

Functions to draw any polygon Jump to this section

import turtle

def draw_polygon(t, n):  # n is the number of sides
    for _ in range(n):
        t.forward(50)
        t.left(360/n)    # calculate the correct angle to turn based on the number of sides

t = turtle.Turtle()

draw_polygon(t,5)  # draw a pentagon

Exercises Jump to this section

  • Write a function triangle(t, size) and use it to draw three triangles.