Turtle Graphics

More on Functions

We can improve our source code by introducing more functions to eliminate the repeated code segments of moving the turtle pointer to the beginning point of each new square:

import turtle

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


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


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

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

turtle.pencolor("Blue")
draw_a_square_for_me(120)
move_turtle_back()

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

turtle.pencolor("Yellow")
draw_a_square_for_me(160)

turtle.done()