Microbit Python Computer Science
Beginner
80 mins
Teacher/Student led
What you need:
Chromebook/Laptop/PC

Functions and Modules

In this lesson, you'll learn the essentials of coding with functions and modules. Explore how to define and use functions for reusable code, work with parameters and return values, and integrate modules to enhance your Micro:bit projects with ease.
Learning Goals Learning Outcomes Teacher Notes

Live Class Feed

This is a live feed of the latest activity by your students on this lesson. It will update in real-time as they work on the lesson.
Load previous activity

    1 - Introduction

    In this lesson you'll be learning to:

    1. Understand functions: Discover how to define and call mini-programs within your code to perform specific tasks, promoting reusability and cleaner code.
    2. Work with parameters and return values: Learn to make functions flexible by passing inputs and getting outputs, allowing them to handle different data without rewriting code.
    3. Explore reusability: See practical examples of how functions reduce duplication, making your programs easier to maintain and debug.
    4. Understand modules: Find out how to import and use pre-written code libraries, like those for the Micro:bit, to add features without starting from scratch.
    5. Import and integrate modules: Practise bringing in modules such as random and music, and combining them with your own functions for interactive Micro:bit projects.
    6. Apply your skills: Complete exercises to create programs that generate random sounds or speech, reinforcing reusability and module usage.

    2 - Understanding Functions

    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.

    3 - Defining a Simple Function

    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.
    Now, run your code and you should see 'Hello' scrolling across the simulated Micro:bit display. If it doesn't work, check your indentation and spelling.
    Experiment to build your understanding: Add another 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. 

    4 - Functions with Parameters

    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.
    Run your code. You should see 'Hello' followed by 'World' scrolling on the display, demonstrating the function's reusability with different inputs.
    Experiment: Add a third call with your name, like 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.

    5 - Functions that Return Values

    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.
    Run your code. You should see '8' scrolling on the display, which is the sum returned by the add_numbers function and then displayed using show_message.
    Experiment: Change the numbers in the 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.

    Unlock the Full Learning Experience

    Get ready to embark on an incredible learning journey! Get access to this lesson and hundreds more in our Digital Skills Curriculum.

    Copyright Notice
    This lesson is copyright of DigitalSkills.org. Unauthorised use, copying or distribution is not allowed.
    🍪 Our website uses cookies to make your browsing experience better. By using our website you agree to our use of cookies. Learn more