2. Micro:bit Functions (MicroPython)
2.1 What are Functions?
Functions are a core concept of programming.
Functions allow us to:
- Group code together
- Give that code a name
- Reuse code instead of rewriting it
This makes programs:
- Easier to read
- Easier to debug
- Easier to build in parts
You can think of a function as a mini-program inside your main program.
2.2 Calling a Function
Calling a function means running the code inside it.
We already use built-in functions on the micro:bit, for example:
1 2 3 | |
Here, display.scroll() is a built-in function.
Functions always use parentheses ().
2.3 Defining a Function
We can create our own functions using def.
Syntax
1 2 | |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
Here we created two functions of our own small_dance and show_heart.
We can then run these as many times as we like by calling them. This is much easier than writing the same code multiple times.
Key Idea
Functions are often used to gather together code that we want to reuse. This makes our program more efficient and easier to read. We write the function once, but can call it many times.
2.4 Parameters (Inputs)
Functions can take inputs called parameters. A parameter is a variable that we pass into the function when we call it. Just like a normal variable we can use it inside the function by calling its name.
This makes them more flexible.
Syntax
1 2 | |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |
Key Idea
Parameters let you reuse the same function with different values.
2.5 Returning Values (Output)
Functions can send a value back using return.
This allows us to store or use the result.
Example 1: Returning a Value
1 2 3 4 5 6 7 8 9 | |
Example 2: Custom Function with Return
1 2 3 4 5 6 7 8 9 | |
2.6 Summary
Functions help us:
- Organise code into reusable blocks
- Avoid repetition
- Make programs easier to understand
Key Concepts
def→ define a function()→ call a function- Parameters → inputs
return→ output
2.7 Class Activity (demo)
-
Create a function that:
- Flashes a heart 3 times
-
Create a function with a parameter:
- Display any message passed in
-
Create a function that:
- Takes a number and returns double the value
-
Extension:
- Use a button press to trigger your function