In this lesson you'll be learning to:
Functions are like mini-programs within your code that perform a specific task. They promote reusability by allowing you to write code once and call it multiple times from different parts of your program, reducing duplication and making your code easier to maintain. For example, if you need to display a message several times, you can define a function to do it and call it whenever needed, rather than rewriting the display code each time.
In Python, you define a function using the def
keyword, followed by the function name and parentheses. The code inside the function is indented. To use the function, you 'call' it by writing its name followed by parentheses. Functions can take inputs (parameters) and return outputs, making them versatile.
Reusability is a key benefit – imagine a function that calculates temperature averages; you can reuse it for different sets of data without rewriting the logic. This saves time, reduces errors, and makes your code cleaner.
Let's start by defining a basic function that scrolls a greeting on the Micro:bit display. This demonstrates the structure: using def
to define it, and then calling it to execute the code inside.
Since it's reusable, we could call it multiple times if needed. Remember, functions help you organise your code better – think of them as building blocks that you can use over and over without rewriting the same lines each time. This makes your programs shorter, easier to read, and less prone to mistakes.
In the Micro:bit Python editor, add the following complete code:
from microbit import *
def show_greeting():
display.scroll("Hello")
show_greeting()
Here's a quick breakdown to make sure you understand each part:
from microbit import *
: This imports the Micro:bit module, which gives you access to features like the display. Without this, you couldn't use display.scroll.def show_greeting():
: This line defines the function. 'def' tells Python you're creating a function, 'show_greeting' is the name you choose (make it descriptive!), and the empty parentheses mean it doesn't take any inputs. The colon (:) indicates the start of the function's code.display.scroll("Hello")
: This is the body of the function – the code that runs when the function is called. It's indented (usually by 4 spaces) to show it belongs to the function. Here, it scrolls 'Hello' on the display.show_greeting()
: This calls (or invokes) the function. Without this, the function is defined but won't run – it's like having a recipe but not cooking the meal.show_greeting()
call after the first one. Run it again – 'Hello' should scroll twice, showing reusability. Change the message inside the function to 'Hi' and test. What happens if you remove the call to show_greeting()
? The function is defined but not executed – try it and see that nothing happens. Parameters allow functions to accept inputs, making them more flexible and reusable. You define parameters inside the parentheses when defining the function, and pass values (which are called arguments) when calling it. This way, the same function can behave differently based on the input, like a greeting function that takes a name and personalises the message.
We'll update our function to take a message parameter and scroll whatever is passed to it. This shows reusability – one function for any message.
Update your code to this complete version:
from microbit import *
def show_message(msg):
display.scroll(msg)
show_message("Hello")
show_message("World")
Here's a quick breakdown:
def show_message(msg):
: Defines the function with a parameter named msg.display.scroll(msg)
: Scrolls the value passed as msg.show_message("Hello")
: Calls the function with 'Hello' as the argument.show_message("World")
: Calls it again with 'World', reusing the function.show_message("YourName")
. Try passing a number converted to string, e.g., show_message(str(42))
. What if you define multiple parameters, like def show_repeat(msg, times):
and use a loop inside? Test simple changes first.Functions can also return values using the return
keyword, allowing them to compute something and send the result back to the caller. This enhances reusability, as you can use the returned value in other parts of your code, like calculations or decisions.
We'll create another function that takes two numbers, adds them, and returns the sum. Then, we'll call it and display the result.
Update your code to this complete version:
from microbit import *
def show_message(msg):
display.scroll(msg)
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
show_message(str(result))
Here's a quick breakdown:
def add_numbers(a, b):
: Defines the function with two parameters, a and b.return a + b
: Computes the sum and returns it to the caller.result = add_numbers(3, 5)
: Calls the function with arguments 3 and 5, storing the returned value (8) in result.show_message(str(result))
: Converts the result to a string and calls show_message to scroll it on the display.add_numbers
function and then displayed using show_message
.add_numbers
call, like add_numbers(10, 20)
, and run again to see the new sum. Try modifying add_numbers
to subtract instead (return a - b) and test with different values. Add another function call and display both results.