Welcome to the lesson on Programming Fundamentals: Variables and Data Types. In this lesson, you'll learn about variables, which are like containers that store information, and different data types such as text, whole numbers, and decimals. We'll use Python with the micro:bit to create an interactive program that displays personal details and performs simple calculations. By the end, you'll have a better understanding of how to handle and manipulate data in code. Let's dive in and start building your programming skills!
Welcome to programming! In this step, you’ll learn about variables. A variable is like a labelled box that holds information, such as your name. In Python, you create a variable by giving it a name and setting its value with the equals sign (=).
Open the micro:bit Python editor at https://python.microbit.org/v/3 and start a new project. You’ll need to import the micro:bit library to use the LED screen.
Add this code to create a variable for your name and display it:
from microbit import *
name = "YourName"
display.scroll("Hello " + name)
Replace YourName
with your actual name (keep the quotation marks—they tell Python it’s text). The first line, from microbit import *
, lets you use the micro:bit’s features. The display.scroll()
function shows your message on the micro:bit’s LED screen.
Now let’s add a variable for your age, which is a whole number. In Python, whole numbers are called integers, and they don’t need quotation marks.
Update your code to include your age:
from microbit import *
name = "YourName"
age = 16
display.scroll("Hello " + name)
display.scroll("Age " + str(age))
Replace 16 with your actual age. The str(age)
part turns your age into text so it can be joined with Age
to display.
Now let’s add your height in metres, which can have decimals. This is called a float in Python.
Update your code to include height:
from microbit import *
name = "YourName"
age = 16
height = 1.75
display.scroll("Hello " + name)
display.scroll("Age " + str(age))
display.scroll("Height " + str(height))
Replace 1.75 with your height in metres (e.g., 1.6). We use "str(height)" to turn the number into text for display.
Run it. You’ll see three messages: your name, age, and height.
Variables can be used to calculate things! Let’s work out how many years until you’re 18.
Update your code:
from microbit import *
name = "YourName"
age = 16
height = 1.75
years_until_18 = 18 - age
display.scroll("Hello " + name)
display.scroll("Age " + str(age))
display.scroll("Height " + str(height))
display.scroll(str(years_until_18) + " years to 18")
The line years_until_18 = 18 - age
creates a new variable by subtracting your age from 18.