4. Python Turtle Subroutines
4. Python Turtle Subroutines
When writing large programs, it is easiest if they can be broken down into sections.
We do this by using subroutines. The following program creates a subroutine to draw
a small square, then calls the subroutines once.
import turtle
def square():
for i in range(4):
turtle.forward(30)
turtle.right(90)
square()
a) Describe what the program does:
To call a subroutine (run it) – type the name of the subroutine in the program
Run create the program above and run it to check that it works.
Task 20
call it nextshape
get it to:
o lift the pen
o move forward 60
o put the pen back down
square()
nextshape()
square()
nextshape()
square()
Task 21
Change the program in Task 20 to now draw 10 shapes in a row – use a loop! (look
back at previous programs if you can’t remember how)
Task 22
Test this by extending the program in Task 21 to now draw 2 rows of 10 squares.
Task 23
You are now going to extend your program to create a 10 x 10 grid of squares.
Things you might want to do:
speed up the turtle by using turtle.speed(0) at the start of your program
create a subroutine gotostart() that moves the turtle up 300 and left 300
before starting the pattern (otherwise it goes off the window)
in the same way that you used a loop to do a row of 10 squares, use a loop to
draw 10 rows of squares
Task 24
To make a multi-coloured grid of squares, think about what you will need to add to
your program. What do you know how to do – what do you not yet know how to do?
See if you can find out the additional commands on the Internet – when searching
remember to include the word python in your search phrase!