Micro:bit MicroPython: Generating random numbers

In this tutorial we will check how to generate a random integer using the micro:bit board and MicroPython.

Introduction

In this tutorial we will check how to generate a random integer using the micro:bit board and MicroPython.

To achieve this, we will use the random module from MicroPython, which offers some simple functions to get random results in our programs.

As already mentioned, we are going to check how to generate a random integer number, but this module offers other interesting functions.

The code

The code for this tutorial will be very simple. So, the first thing we will do is importing the random module, so we have access to the function we need to generate the random integer.

import random

Then, we simply need to call the randint function, in order to generate a random integer. As input, this function receives a start and an end integer parameters, which determine the range of values from which the random integer will be generated.

So, if we pass a start value of 0 and an end value of 10 (like in the code below), we will get a random number between 0 and 10. Note that the start and end values are included in the interval of possible numbers that will be generated [1].

print(random.randint(0,10))

Just to obtain some additional results, we will do a couple more calls to the randint function.

print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))

The final complete code can be seen below.

import random

print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))
print(random.randint(0,10))

Testing the code

To test the code, run the previous script on the micro:bit using a tool of your choice. I’ll be using uPyCraft, a MicroPython IDE.

Upon running the code, you should get an output similar to figure 1. Naturally, the numbers you will obtain will probably be different from mine, due to the fact that they were generated randomly.

Generating random numbers with the Micro:bit and uPython
Figure 1 – Random numbers generated by the Micro:bit

References

[1] https://microbit-micropython.readthedocs.io/en/latest/tutorials/random.html

Leave a Reply

%d bloggers like this: