MicroPython — random numbers and basic algorithms

Lesson 6 of 17 · MicroPython and the micro:bit

In many games and projects the computer needs to make random decisions or to process data by certain rules. In this lesson you will learn how random numbers are used in MicroPython and what simple algorithms look like.


Random numbers (random)


MicroPython has the module random for generating random numbers. This is often used in games, simulations and mini projects.



import random

# generates a whole number between 1 and 6
number = random.randint(1, 6)
print(number)

The function randint(a, b) returns a whole number between a and b, including both ends.


Example 1: rolling a die



from microbit import *
import random

while True:
    # a random number from 1 to 6
    die = random.randint(1, 6)
    display.show(die)   # show the number on the LED matrix
    sleep(1000)         # wait 1 second before the next roll

Every second a new number from 1 to 6 is shown — like rolling a die.


Example 2: a random animation of a heart and a smile


from microbit import *
import random

pictures = [Image.HEART, Image.HAPPY, Image.SAD]

while True:
    choice = random.choice(pictures)  # chooses a random picture from the list
    display.show(choice)
    sleep(500)

random.choice(list) chooses a random element from a list — handy for mini games and animations.


What is an algorithm?


An algorithm is an exact order of steps that solves a problem. In programming this means:

  • take the data
  • process it by rules
  • get a result

An example of a simple algorithm



number = 7

if number > 5:
    display.scroll("More than 5")
else:
    display.scroll("5 or less")

This program checks whether the number is greater than 5 and shows a message.


Working with lists and algorithms


Lists (arrays) are often used to keep several values. We can apply algorithms to them.



numbers = [3, 7, 2, 9, 5]

# finding the largest number
largest = numbers[0]
for n in numbers:
    if n > largest:
        largest = n

display.scroll(largest)

This is an example of an algorithm for finding the maximum.


Example: finding the smallest number


smallest = numbers[0]
for n in numbers:
    if n < smallest:
        smallest = n

display.scroll(smallest)

Simple sorting (the idea)


Sorting means arranging the numbers from the smallest to the largest. In MicroPython it is often enough to understand the idea, not perfect efficiency.



numbers = [4, 1, 3, 2]

for i in range(len(numbers)):
    for j in range(i + 1, len(numbers)):
        if numbers[j] < numbers[i]:
            numbers[i], numbers[j] = numbers[j], numbers[i]

display.scroll(numbers[0])  # show the smallest number

Connecting with earlier lessons


This lesson connects naturally with:


Mini tasks — practising random numbers and algorithms


Task 1

Make a program that shows a random number from 1 to 10 on the LED matrix every second. Add sleep() so that the animation is not too fast.


Task 2

Create a list of 7 random numbers (0–9) and write an algorithm that finds the largest number and shows it.


Task 3

Make a mini game:

  • Press button A to generate a random number from 1 to 6.
  • Press button B to check whether the number is greater than 3 and show the matching picture (HEART or SAD).

Task 4 (challenge)

Make a program that generates 10 random numbers, keeps them in a list and counts how many of them are greater than 5. Show the result on the LED matrix.


Task 5 (advanced)

Make an animation with a random choice of pictures (HEART, HAPPY, SAD). Every time button A is pressed, change the picture to a new random one. Combine while True, if button_a.is_pressed() and random.choice().


Connecting with control statements and variables


In MakeCode you learned how variables and control statements (if/then) work together in projects such as click counters and mini games. You can find those examples and explanations on the page:
Using variables and control statements in micro:bit projects

On that page you will see practical examples of using variables and control statements in the MakeCode environment — such as:

  • a counter of presses of button A
  • combining A, B and A+B for different actions
  • arithmetic operations and showing the result

It is an excellent basis for understanding how to implement the same ideas in MicroPython.

5 examples in MicroPython


Example 1 — A press counter

A counter of presses of button A: every press increases a variable and shows it.


from microbit import *

clicks = 0

while True:
    if button_a.was_pressed():  # detects a press of A
        clicks += 1             # increases the counter
        display.show(clicks)
    sleep(100)

This is the MicroPython equivalent of the MakeCode click counter from the Variables palette.


Example 2 — Interactive calculation with numbers

Press A to generate a random number a, B to generate b, and A+B to show their product.


from microbit import *
import random

a = 0
b = 0

while True:
    if button_a.was_pressed():
        a = random.randint(1,10)
        display.show(a)
    if button_b.was_pressed():
        b = random.randint(1,10)
        display.show(b)
    if button_a.is_pressed() and button_b.is_pressed():
        product = a * b
        display.show(product)
    sleep(100)

This is the Python version of the MakeCode example with the product of numbers.


Example 3 — Numbers greater than the mean

Generate a list of random numbers and show how many of them are greater than the mean of the list.


from microbit import *
import random

while True:
    values = [random.randint(0,9) for _ in range(7)]
    mean = sum(values) / len(values)
    count = 0
    for n in values:
        if n > mean:
            count += 1
    display.show(count)
    sleep(2000)

The example combines random numbers, lists, loops and algorithmic data processing — all topics that build on MakeCode variables and Math.


Example 4 — Adding pairs

Generate a pair of random numbers and show their sum when A+B is pressed.


from microbit import *
import random

x = random.randint(0,10)
y = random.randint(0,10)

while True:
    if button_a.was_pressed():
        display.show(x)
    if button_b.was_pressed():
        display.show(y)
    if button_a.is_pressed() and button_b.is_pressed():
        total = x + y
        display.show(total)
    sleep(100)

You practise working with variables and branching on conditions — the equivalent of MakeCode addition from the Math palette.


Example 5 — A maths challenge: a square and a linear function

Press A to show the square of a random number, and B to show a linear function (for example 2n+1).


from microbit import *
import random

while True:
    if button_a.was_pressed():
        n = random.randint(0,9)
        display.show(n * n)   # the square of the number
    if button_b.was_pressed():
        m = random.randint(0,9)
        display.show(2*m + 1) # the linear function 2n+1
    sleep(100)

This example builds on the MakeCode maths operations using MicroPython arithmetic.

Practical tasks — random numbers and algorithms


In these tasks you will practise working with random numbers, variables and control statements in MicroPython, compared with the MakeCode version.


Task 1 — A counter of random clicks

Make a counter of presses of button A, but every press adds a random number from 1 to 3 instead of 1.


from microbit import *
import random

counter = 0

while True:
    if button_a.was_pressed():
        counter += random.randint(1,3)
        display.show(counter)
    sleep(100)

The difference from MakeCode: in MakeCode you would use a variable and the block "change variable by pick random 1 to 3", while MicroPython uses the function random.randint() and ordinary arithmetic.


Task 2 — A random animation

Create an animation that shows a randomly chosen icon (HEART, HAPPY, SAD) on the LED matrix every second.


from microbit import *
import random

icons = [Image.HEART, Image.HAPPY, Image.SAD]

while True:
    choice = random.choice(icons)
    display.show(choice)
    sleep(1000)

The difference from MakeCode: in MakeCode you imitate a "pick random" block that chooses from a list of icons, while MicroPython uses random.choice().


Task 3 — A guessing game

Show a random number from 1 to 5. If the user presses button A, check whether they hit the number 3 and show OK or X.


from microbit import *
import random

while True:
    number = random.randint(1,5)
    display.show(number)
    sleep(500)
    if button_a.was_pressed():
        if number == 3:
            display.show("OK")
        else:
            display.show("X")
    sleep(500)

The difference from MakeCode: MakeCode uses "if then else" blocks and a variable for the random number, MicroPython uses an ordinary if/else and random.randint().


Task 4 — Adding random numbers

Every press of button B generates a new random number 0-9. A press of button A shows the sum of all the numbers generated so far.


from microbit import *
import random

total = 0

while True:
    if button_b.was_pressed():
        n = random.randint(0,9)
        total += n
        display.show(n)
    if button_a.was_pressed():
        display.scroll(total)
    sleep(100)

The difference from MakeCode: in MakeCode you use a variable "total" and the blocks "change variable by pick random" and "show number"; in MicroPython you use a variable and the += operator.


Task 5 — A mini counting game with a limit

Generate 10 random numbers 1-6 and show how many of them are greater than 3. A press of button A shows the result.


from microbit import *
import random

values = [random.randint(1,6) for _ in range(10)]

while True:
    if button_a.was_pressed():
        count = 0
        for n in values:
            if n > 3:
                count += 1
        display.scroll(count)
    sleep(100)

The difference from MakeCode: MakeCode uses the "for each item in list" block, "if then" and variables; MicroPython uses an ordinary for loop and an if condition.


Related: the same topic in MakeCode and other lessons

If you worked with the micro:bit in blocks in the 5th or 6th grade, compare the blocks with the MicroPython code:

Check your knowledge

Open the quiz

Mini quiz: random numbers

1. Which numbers can random.randint(1, 6) return?




2. What must be at the start of the program for random.randint to work?