Turtle Graphics

Functions in Python

Although they are interchangeable in many programming languages, Python uses the term function for non-object related functional units of code and the term method for object related functional units of code. We will concentrate on functions for the time being.

A function is defined with the def keyword.

The following code defines a function with an argument that is used inside the function to drawing squares of variable sizes:

import turtle

def draw_a_square_for_me(square_size):
    turtle.forward(square_size)
    turtle.right(90)
    turtle.forward(square_size)
    turtle.right(90)
    turtle.forward(square_size)
    turtle.right(90)
    turtle.forward(square_size)
    turtle.right(90)


turtle.penup()
turtle.goto(-50,50)
turtle.pendown()
turtle.pensize(5)

turtle.pencolor("Red")
draw_a_square_for_me(100)

turtle.penup()
turtle.backward(10)
turtle.left(90)
turtle.forward(10)
turtle.right(90)
turtle.pendown()
turtle.pencolor("Blue")
draw_a_square_for_me(120)

turtle.penup()
turtle.backward(10)
turtle.left(90)
turtle.forward(10)
turtle.right(90)
turtle.pendown()

turtle.pencolor("Green")
draw_a_square_for_me(140)

turtle.done()

Caution: Defining a function does not mean that the function will be executed immediately. The execution takes place when the function name is encountered inside a statement line (without the def keyword) with values or variables passed to the function as arguments if any arguments were specified during the definition of the function. The correct number of arguments must be provided during the function call.

def tells the Python interpreter to start defining the internal structure of a function and be prepared to execute the given set of instructions in that function as soon as a function call statement is issued in the running program.