Microbit Python
Intermediate
60 mins
Teacher/Student led
220 points
What you need:
Chromebook/Laptop/PC
Microbit

Looping Around

In this step-by-step lesson, you'll delve into Python loops, starting with understanding indentations and how they define code blocks. You'll explore 'while' and 'for' loops, and how to use them effectively. You'll also learn about nested loops and how to break out of loops. Finally, you'll apply your knowledge to create a fun reaction time game.
Learning Goals Learning Outcomes Teacher Notes Lesson Files

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 will learn about different types of loops in Python, such as while loops, for loops, and nested loops. You will also learn how to use indentations and break out of loops.

    2 - Understanding Indentations

    Python uses indentation to define code blocks, unlike many programming languages which use braces { }.

    Defining code blocks means grouping lines of code together that should be executed as a single unit. This is important for controlling the flow of your program, especially when using loops and conditional statements.

    Here is an example in JavaScript which uses curly braces:

    if button_a.is_pressed(){
    	display.show("A")
    }

    Here is an example in Python which uses indentation:

    if button_a.is_pressed():
        display.show("A")

    To indent your code in Python, you can use the Tab key on your keyboard. Pressing the Tab key will move the cursor to the right, creating an indentation. Make sure to use consistent indentation throughout your code, as it is crucial for the proper functioning of your program.

    Create a new project using python.microbit.org and add the following python code:

    if button_a.is_pressed():
    	display.show("A")

    Then remove the indent so the code looks like this:

    if button_a.is_pressed():
    display.show("A")

    The editor will show you that there is an error.



    3 - Introduction to 'while' loops

    In programming, loops are used to repeat a block of code multiple times. They are useful when you want to perform a task repeatedly or iterate through a collection of items. In this step, we will learn about 'while' loops in Python.

    A while loop executes as long as the condition is true.

    Infinite Loop
    An infinite loop never stops running.

    while True:
        display.show("!")

    Conditional Loop
    Runs as long as the condition remains true.

    count = 0
    while count < 5:
        display.show(str(count))
        sleep(1000)
        count += 1

    Try out both of these loops in the code editor and run your code.

    After you've tried them both out, change the while loop to run only 3 times.


    4 - Introduction to 'for' loops

    A for loop is a control flow statement that allows you to iterate over a sequence of values. This is useful when you want to perform a specific action for a certain number of times or for each item in a list or other iterable objects.

    When using a for loop with the range() function, the loop starts at 0 by default. This is because Python uses zero-based indexing, which means the first element in a sequence has an index of 0.

    Now, let's explore some examples of for loops:

    The following code will loop through the numbers 0 to 4:

    for i in range(5):
        display.show(str(i))
        sleep(1000)

    The following code will loop through the numbers 1 to 5:

    for i in range(1, 6):
        display.show(str(i))
        sleep(1000)

    Try out both of these loops in the code editor. Delete your previous code (apart from the import line) and then add the new code and run it.

    Change the range and see the effect it has.



    5 - Exploring Nested Loops

    Nested loops are loops within loops, where an inner loop is executed for each iteration of the outer loop.

    The following code is a nested loop:

    for y in range(5):
        for x in range(5):
            display.clear()          # Clear previous LED state
            display.set_pixel(x, y, 9)  # Set the LED at position (x, y) to its brightest
            sleep(200)               # Wait for a short time to visualize the LED movement

    In this example:

    • The outer loop for y in range(5) iterates through the rows of the micro:bit's 5x5 LED matrix.
    • The inner loop for x in range(5) iterates through the columns.
    • Combined, these loops make a light "travel" from the top-left corner (0,0) to the bottom-right corner (4,4) of the micro:bit's display, moving left-to-right and then top-to-bottom.

    Let's understand how the x and y values are being updated:

    • Initially, y is set to 0, and the inner loop starts executing (the top row).
    • For each value of y, the x value goes from 0 to 4, controlling the position of the light on the matrix (each column).
    • When the inner loop completes its iterations for x, the outer loop increments the value of y by 1 and the inner loop starts again with x = 0 (the next row).
    • This process continues until the outer loop has iterated through all the values of y (0 to 4).

    Try out the above code in the editor and notice how the light moves through the LED positions.


    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