Variables, lists and functions in MicroPython
So that a program can remember data, repeat actions and solve more complex tasks, we use variables, lists (arrays) and functions.
These ideas are very important because they are used all the time in projects, games and algorithms (for example sorting, counting steps, sensor measurements).
Variables
A variable is a place in memory where we keep a value. The value can change while the program is running.
from microbit import *
# Examples of variables
number = 5 # a whole number
temperature = 23 # a measurement in °C
name = "Ana" # text
display.scroll(number) # shows "5" on the LED matrix
In MicroPython you do not need to state the type of a variable — Python recognises by itself whether it is a number, text or something else.
Lists (arrays)
A list (array) is a variable that can hold several values. We use it when we have several pieces of data of the same type.
# A list of numbers
numbers = [3, 7, 2, 9, 5]
display.scroll(numbers[0]) # the first element: 3
We access the elements of a list with an index. Indexes start from 0.
numbers[2] = 10 # we change the third element (it was 2)
A loop through a list
numbers = [1, 2, 3, 4]
for number in numbers:
display.show(number)
sleep(500) # half a second between the displays
This is very useful for processing sensor measurements or showing a series of values.
Functions
A function is a part of the code that does a certain job and can be called many times.
def greet():
display.scroll("Hello!")
We call a function simply by its name:
greet()
Functions with parameters
def show_number(number):
display.show(number)
show_number(7)
Parameters let the same function work with different values.
Example: processing data from a list
readings = [20, 21, 22, 23]
def average_temperature(values):
total = 0
for value in values:
total += value
return total / len(values)
avg = average_temperature(readings)
display.scroll(int(avg))
You will use this idea in projects with sensors and data analysis.
Mini tasks (explained in detail)
Task 1 — Showing numbers
Make a list of 5 numbers of your choice. Use a for loop to show each number on the LED matrix with a 500 ms pause between the displays.
# A list of numbers
numbers = [4, 7, 1, 9, 3]
for number in numbers:
display.show(number)
sleep(500)
Task 2 — A function for a message
Make a function show_name that takes a name and shows it on the matrix. Call the function with your name.
def show_name(name):
display.scroll(name)
show_name("Ana")
Task 3 — Combining a list and a function
Make a list of 3 numbers. Write a function that returns the sum of the numbers in the list and show the result.
def sum_of_numbers(values):
total = 0
for n in values:
total += n
return total
my_numbers = [5, 2, 8]
result = sum_of_numbers(my_numbers)
display.scroll(result)
Task 4 — A number animation
Make a list of 5 numbers and with a for loop show each number for 1 second, and then in reverse, from the last to the first.
numbers = [1, 2, 3, 4, 5]
# Forwards
for n in numbers:
display.show(n)
sleep(1000)
# Backwards
for n in reversed(numbers):
display.show(n)
sleep(1000)
Task 5 — Combining with the buttons
While the user holds button A, the first list of numbers is shown. While they hold button B, the second list is shown.
from microbit import *
list_A = [1,2,3]
list_B = [9,8,7]
while True:
if button_a.is_pressed():
for n in list_A:
display.show(n)
sleep(500)
elif button_b.is_pressed():
for n in list_B:
display.show(n)
sleep(500)
Mini tasks for independent work
Tasks similar to the previous ones, but with minimal hints — good for practice and experimenting.
- Make a function that takes a list of numbers and shows only the even numbers.
- Make a list of 4 pictures (
Image) and show them as an animation. - Write a function that returns the biggest number in a list and use it for an animation.
- Make a list of 5 numbers and show them on the LED matrix while button A is pressed.
- Write a function that takes a name and a number, and shows the name and the number on the LED matrix with a delay of 500 ms.
A link to an extra lesson
You can find more examples and practical uses of variables in micro:bit projects on the page: Using variables in micro:bit projects
On that page you will learn how variables help in making counters, quizzes and animations with sensors.
Hidden mini quiz — variables, lists and functions
Click on the quiz and check whether you understand the basic concepts: variables, lists and functions in MicroPython.
Open the quiz
Mini quiz: variables, lists and functions
1. Which variable keeps text?
name = "Ana"
number = 5
2. What does len(numbers) return?
numbers = [1,2,3,4]
3. How do we call the function greet()?
4. Which code shows all the elements of a list on the LED matrix?
numbers = [2, 4, 6]
5. What does a function return if it has no return?
def test():
x = 5
Connecting with micro:bit games
If you want to apply what you have learned about variables, lists and functions, look at the lesson: Games and the micro:bit .
There you will learn how functions are used for:
- starting and stopping a game
- showing animations of the player and the obstacles
- keeping track of the score and the state of the game with variables and lists
Examples in MicroPython
1. Showing the player's number of lives on the LED matrix:
from microbit import *
lives = 3
def show_lives():
display.show(lives)
while True:
show_lives()
sleep(1000)
Explanation:
- The variable
liveskeeps the number of lives. - The function
show_lives()shows the value on the LED matrix. - The infinite loop keeps refreshing the display.
2. An animation of obstacles:
obstacles = [Image.ARROW_N, Image.ARROW_W, Image.ARROW_E]
while True:
for o in obstacles:
display.show(o)
sleep(500)
Explanation:
- The list
obstacleskeeps a series of pictures of obstacles. - The
forloop goes through all the obstacles and shows them on the LED matrix.
3. A function that reacts to a button:
def button_action():
if button_a.is_pressed():
display.show("A")
elif button_b.is_pressed():
display.show("B")
while True:
button_action()
sleep(100)
Explanation:
- The function
button_action()checks the buttons and reacts. - The infinite loop keeps calling the function and follows what the user does.
These examples show how combining variables, lists and functions helps in making interactive games.
Mini projects — micro:bit games and experiments
These tasks combine the previous lessons and help you put variables, lists, functions, buttons and the LED matrix into practice.
Task 1: A button press counter
Create a program that counts how many times button A has been pressed and shows the result on the LED matrix.
Instructions:
- Make a variable
press_countthat keeps the number of presses. - Use
button_a.is_pressed()to detect a press. - Create a function
show_count()that shows the current number of presses on the LED matrix. - Add a short pause (
sleep()) between readings so that the counting is stable.
Note: an excellent example for learning to combine variables and functions with buttons.
Task 2: A number animation
Show the numbers from 1 to 5 one by one on the LED matrix, then go back to 1 and continue in an infinite loop.
Instructions:
- Make a list
numbers = [1,2,3,4,5]. - Create a function
show_numbers()that uses aforloop to show each number with a pause. - Use
while Trueso that the animation keeps repeating.
Note: this task practises a list, a loop and a function at once.
Task 3: A mini game — avoiding obstacles
Simulate a game in which your character (an LED dot) "runs away" from obstacles that appear on the LED matrix.
Instructions:
- Create a variable
player = Image("00100:00100:00100:00100:00100")or something similar. - Make a list of pictures of obstacles, for example
obstacles = [Image.ARROW_N, Image.ARROW_W, Image.ARROW_E]. - Create the functions
show_player()andshow_obstacles(). - Use
button_aandbutton_bto move the player left/right. - Use
while Trueandsleep()for the animation.
Note: an excellent project for combining everything we have learned: variables, lists, functions, buttons and the LED matrix.
Task 4: A counter of animated hearts
Make a program that shows a heart animation, and every time button A is pressed, increases the "number of hearts" and shows it.
Instructions:
- Create a variable
heart_countand set it to 1. - Create a function
show_hearts()that uses aforloop to showheart_counthearts in the animation. - Pressing button A increases
heart_count. - Add
sleep()so that the animation is not too fast.
Note: practises combining variables and animation in functions.
Task 5: A timer / countdown
Create a timer that counts down from 10 to 0 and shows the result on the LED matrix, and when it reaches 0, shows "End!".
Instructions:
- Create a variable
timer = 10. - Create a function
show_timer()that shows the current number. - Use a
whileloop to decreasetimerand addsleep(1000)between the steps. - At the end show the text "End!" with
display.scroll().
Note: practises variables, functions and loops with time.
