Lesson 5
Functions
By the end of this lesson, you will…
Learning Objectives
What is a function?
“Make me a cup of tea please”
How do you make a cup of tea?
What steps are involved?
How do we know this?
A function is a command which contains the steps needed to perform a task
Lesson 5
How does a function work?
We are going to create a function to draw 10 circles in a pattern
We have now created a function. But we need to add code to the function. This is the code that will be ran when the function is called.
Lesson 5
Using the function
We import turtle as per previous lessons.
The circles function will use a for loop. It will go round 10 times.
It will draw a circle with a radius of 20 pixels, then turn left by 36 degrees (360/10)
We then call the circles function and watch as it automatically draws the pattern.
Run the code, what happens? Does it work as expected?
Can you change it to do something else?
Lesson 5
A function with an argument?
We are going to create a function to draw any shape using Turtle
The code inside the function is run when the function is called.
Lesson 5
Code inside the function
Inside of the function we add:
Lesson 5
Using a function
Inside a while True loop:
Lesson 5
Using a function
What if we let the user decide on n:
Lesson 5
Importing the turtle blocks if you haven’t already.
Your code should look like this, click to test
Lesson 5
What happens?
By using the name sides, we call the function.
The user input captures the number of sides the shape has. This is saved to n which is then used to control the for loop.
It also forms part of the calculation to determine the turning angle.
Lesson 5
Why are functions useful?
Functions are powerful tools.
They are subroutines, small sequences of code inside the main code.
We can call the function, and come out of the main code, do the function, then come back to the code.
They enable us to reuse sections of code.
They keep our code tidy, and with fewer lines to write.
In our code we can draw any shape using one section of code.
Lesson 5
What have we learnt?
Plenary
Next Lesson
Next Lesson we will use EduBlocks to build our own projects to create patterns using shapes and colours
Plenary