Python – Subroutines
Remember, save each program with the task number.
Task 19
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:
When creating a subroutine:
def stands for define, and tells they program you are defining a subroutine
this is then followed by the name of the subroutine (square in this case)
followed by 2 brackets and a colon
the contents of the subroutine are indented
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
Create a new subroutine:
call it nextshape
get it to:
o lift the pen
o move forward 60
o put the pen back down
Create a program that uses the subroutine to draw 3 squares:
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
Create a subroutine called nextrow which:
lifts the pen
goes backwards 600
moves down 60
ends pointing to the right again
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!