Now, we’re going to learn how to use functions: a way to execute a series of codes that we want to use multiple times without dragging the same blocks every time we need to use them. Think of functions as a shortcut of sorts!
Components Needed
Little Python Brain
A tablet/phone/laptop
Steps
1
Setting variables
First up, we’re going to set up 2 variables: x and y.
Simply get two variable = value block from the Setup category.
2
Setting x and y as variables
Change the first one to x = 64
Change the second to y = 32
3
Defining functions
Functions are a convenient way to execute a couple of lines of codes at once. We will make a function for showing the pixel on the screen. There are two elements to the f(x) block:
f – defines the name of the function
x – defines optional variable/s that a function will take
4
Setting the function
For now, we’ll just be renaming f to movePixel and removing the x.
5
What to put inside the function
We will then move the oled blocks from last lesson and changing the oled.pixel() parameters back to x and y.
6
Calling the function
Finally, now that we set the function, we will call it. In order to call the function that we defined from step 3, simply type in the name of the function. In this case, we can just call movePixel(). Run the code
The Complete Code
Run the code and note where the pixel is! In the next lesson, we’ll be using the touchpads to move the pixel around