Skip to content

User guide

Python guide

Get started coding your micro:bit with Python, one of the world's most popular programming languages

This guide shows you how to use each feature of the micro:bit in Python, with short example code and links to quick, practical projects.

Online editor

Our online microbit Python Editor is designed with teachers and learners in mind with many features designed to overcome common barriers to learning including built-in code samples, a simulator, code-structure highlighting, syntax-checking, auto-complete and more.

We recommend using the built-in reference content in the online editor, which has a greater scope than the code examples in this page.

Screen shot of the micro:bit Python Editor
Try the online Python editor

Hello, World!

Let's start by making some words and a picture appear on your micro:bit's display. Go to the Python editor and you’ll see this program:

Flash it to your micro:bit by downloading a hex file and transferring it, or flash it by webUSB, and see words and pictures appear on your micro:bit.

You need to be very precise when coding in text-based languages, and Python is no exception. The spaces at the start of lines 6, 7 and 8 are important. These are called indentations, made from four space characters (or one press of the TAB key.)

You’ll notice that Python programs often use a while True: statement. This is an infinite loop like the forever block in MakeCode or Scratch. The instructions indented after while True: form part of the loop: your micro:bit will keep carrying out those instructions as long as it has power.

Any instructions after while True: that are not indented won't be carried out until the loop has finished.

The Set-up page explains more about connecting and transferring code to your micro:bit:

Images

As well as showing a HEART icon, like in the example above, you can use lots more built-in images with Python. Try HAPPY, DUCK or GHOST. You'll find a list of all the built-in images in the micro:bit Python reference guide.

You can also make your own pictures this example. Try different numbers from 0 to 9 to make each LED darker or brighter:

These three projects put Python images to use and give you ideas for taking them further:

Light up your micro:bit with love by showing a heart

Make your micro:bit’s heart beat using loops

Buttons

Unlike MakeCode, Python on the micro:bit doesn’t have event blocks like ‘on button A pressed’. Instead, we use the infinite while True: loop to keep checking if a button has been pressed. (Actually, MakeCode programs do the same thing when they run on your micro:bit, but MakeCode hides the infinite loop from you when you’re writing your code.)

Can you guess what this program does? Try it out!

Here are three projects using button inputs in Python for you to try:

Use your micro:bit to express how you’re feeling

Use buttons to play different tunes

Sensors

The micro:bit has many built-in sensors which you can access in your Python programs to interact with the world around you.

Accelerometer

Gestures

The micro:bit has an accelerometer input sensor built-in which measures physical forces. You can use to make things happen when you move your micro:bit in certain ways, such as when you shake it, drop it, turn it on its side, face up or face down. These movements are called gestures.

1from microbit import *
2
3while True:
4    if accelerometer.was_gesture('shake'):
5        display.show(Image.SILLY)
6        sleep(2000)
7    if accelerometer.was_gesture('face up'):
8        display.show(Image.HAPPY)
9    if accelerometer.was_gesture('left'):
10        display.show('<')
11    if accelerometer.was_gesture('right'):
12        display.show('>')

These three makes show you practical and fun uses for gestures:

Shake your micro:bit to make random numbers

Make your own step counter with a micro:bit

Data

You can also get more accurate readings of forces from the micro:bit’s accelerometer in 3 dimensions. This program works as a kind of spirit level, showing a dash if it’s level, or showing arrows to tell you which way it’s leaning if it’s not flat on your desk. It does this by measuring forces just in the x-axis:

1from microbit import *
2
3while True:
4    reading = accelerometer.get_x()
5    if reading > 20:
6        display.show(">")
7    elif reading < -20:
8        display.show("<")
9    else: display.show("-")
micro:bit showing X axis going across the front, Y axis going down and up, Z axis going back to front

Here are three programs that use accelerometer data in practical ways:

Explore all accelerometer projects

Temperature

The micro:bit’s processor contains a temperature sensor which you can use in your programs. It’s a useful approximation of the temperature around your micro:bit. This program shows how warm or cold your micro:bit is in °C when you press button A:

Learn about the temperature sensor

You could use any of these three projects in your classroom or home to monitor and log temperature data:

Make a simple thermometer with your micro:bit

Explore all temperature projects

Light

The LED display on the front of your micro:bit can also detect light, acting as a sensor input as well as an output. Try this simple nightlight project: shine a light on your micro:bit, then cover it or turn out the lights and you should see the display light up.

These three practical projects use light sensor data to trigger different outputs:

Create a light that turns on when it’s dark

Make an alarm that goes off when lights go on

Explore all light sensor projects

Compass

Your micro:bit has an input sensor for measuring magnetic fields, which you can use as a compass. This project tells you, once you’ve calibrated it by playing a little game, what compass bearing the top of your micro:bit is pointing towards.

diagram showing a compass rose and micro:bit

Here are three projects using the compass and magnetometer to measure the strength of a magnetic field:

Create a simple compass to show which way is North

The new micro:bit with sound has a gold logo on the front that works as a touch sensor. Here's how to use it an extra input button in your projects:

Explore other ways of using the touch logo in these three projects:

Sound

With Python your micro:bit can make music, express itself - and even speak!

Music

headphones connected to pin 0 and GND pin of micro:bit using crocodile clip leads

Attach headphones to pin 0 and GND on your micro:bit and you can use it to make noise and play music. There are many more built-in tunes to enjoy, try ODE, BLUES or BIRTHDAY - or compose your own. If you have a new micro:bit with sound, the music will also play from the built-in speaker.

Explore music further with these three makes:

Use buttons to play different tunes

Explore all sound projects

Speech

Your micro:bit can talk when you import the speech module. How could you add speech to improve a project like a compass or thermometer to make it more accessible?

Speech reference guide

Speaker

Expressive sounds

The new micro:bit with a built-in speaker can also play expressive sounds like giggles, yawns and greet you with a 'hello'. The Sound emotion badge project uses three of them:

1from microbit import *
2import audio
3
4while True:
5    if button_a.is_pressed():
6        display.show(Image.HAPPY)
7        audio.play(Sound.HAPPY)
8    if button_b.is_pressed():
9        display.show(Image.SAD)
10        audio.play(Sound.SAD)
11    if pin_logo.is_touched():
12        display.show(Image.SURPRISED)
13        audio.play(Sound.SPRING)

The full list of expressive sounds includes GIGGLE, HAPPY, HELLO, MYSTERIOUS, SAD, SLIDE, SOARING, SPRING, TWINKLE and YAWN. Try them out and see which ones best add personality to your project.

Muting the speaker

Any sound you make with the micro:bit will come out of the new micro:bit's built-in speaker and pin 0 by default. You can mute the speaker using pin_speaker.disable() and the sound will still go to any headphones connected to pin 0.

Microphone

The new micro:bit has a built-in microphone that can detect loud and quiet events, and also measure how loud a sound is.

This simple Clap hearts program reacts to current loud sounds like claps to animate a heart:

1from microbit import *
2
3while True:
4    if microphone.current_event() == SoundEvent.LOUD:
5        display.show(Image.HEART)
6        sleep(200)
7    if microphone.current_event() == SoundEvent.QUIET:
8        display.show(Image.HEART_SMALL)

You can set the threshold for loud and quiet events using numbers from 0-255, with 0 being the quietest and 255 the loudest.

You can also check the last sound event rather than the current one, like in this Clap-o-meter program that measures the duration of loud sounds:

1from microbit import *
2microphone.set_threshold(SoundEvent.LOUD, 150)
3start = 0
4
5while True:
6    if microphone.was_event(SoundEvent.LOUD):
7        start = running_time()
8        display.show(Image.TARGET)
9
10    if microphone.was_event(SoundEvent.QUIET):
11        if start > 0:
12            time = running_time() - start
13            start = 0
14            display.clear()
15            sleep(100)
16            display.scroll(time / 1000)

You can use microphone.sound_level() to measure how loud sounds are. This Disco lights program makes the LED display glow brighter the louder sounds picked up by the microphone are:

Explore these and other sound measuring projects in more depth:

Clap your hands to make the micro:bit heart beat

Random numbers

You can add more functions to Python on your micro:bit by importing modules. This program imports the random module so we can make a simple random number generator like dice:

Random numbers reference guide

Shake your micro:bit to make random numbers

Radio

Two or more micro:bits can communicate wirelessly using the radio module. Flash this program on to two micro:bits and see what happens when you shake each in turn:

1from microbit import *
2import radio
3radio.config(group=23)
4radio.on()
5
6while True:
7    message = radio.receive()
8    if message:
9        display.show(Image.DUCK)
10    if accelerometer.was_gesture('shake'):
11        display.clear()
12        radio.send('duck')
13

There are over a dozen Python projects using radio. Here are three to get you started:

Explore all radio projects

Pins

The strip of golden 'teeth' at the bottom of your micro:bit allow you to connect it to electronics such as switches, sensors, lights, motors - and even other micro:bits.

Get started expanding your micro:bit with these three makes:

Explore all pins projects

Networking

You can communicate securely over wires with two micro:bits (no-one can snoop on your radio messages!) and learn about computer networking.

Nominet have also written a Python version of their book Networking with the micro:bit which covers wired and wireless networking.

Networking reference guide

Adding modules

You can access the micro:bit's Python file system to add Python modules to extend your programs or make using accessories easier.

Learn how to add files and modules

Serial (REPL)

The serial REPL (Read-Evaluate-Print-Loop) feature lets you type Python commands on your computer and run them immediately on your micro:bit without the need to flash a whole program. Connect using webUSB, flash any Python program onto your micro:bit then click on the 'Open Serial' button, and click on the Ctrl-C button.

Type import love into the REPL, press enter and see what happens to your micro:bit!

The serial feature is also helpful for debugging programs as you can use it to read any Python error messages from your micro:bit. Switch to the serial mode and reset your micro:bit and you'll see any error messages on your computer screen as well as scrolling across the micro:bit's display.

Find out more about the REPL

Next steps

Always experiment, always explore, always learn!

Once you get used to the concepts in this guide, read the full Python documentation to learn how to take things further.

micro:bit Python reference guide