micropython-variables-tipos-datos

Variables and Data Types in MicroPython

  • 5 min

We continue exploring the basic syntax of MicroPython. In this tutorial, we will see how to work with variables and data types.

Although MicroPython is a stripped-down version of Python, it essentially shares the same types and way of working with variables as its “older sibling”.

So let’s briefly review it. When there is a significant difference between MicroPython and Python, I will point it out.

What Are Variables?

A variable is a space in memory that stores a value that can change during the execution of a program.

In Python and MicroPython, variables are declared dynamically, and their type is inferred automatically based on the value assigned to them (meaning that it is not necessary to specify their type).

my_variable = 10

In this case,

  • my_variable is a variable that stores the value 10.
  • MicroPython infers that the type of my_variable is an integer (int).

Reassigning Variables

One of the features of Python (and shared by MicroPython) is that variables can change type during the execution of the program.

my_variable = 10      # Now it is an integer
my_variable = "Hello" # Now it is a string

This is possible because Python is a dynamically typed language. That is, the type of variables is not fixed.

However, in MicroPython, where resources are limited, it is advisable to avoid unnecessary type changes to optimize memory usage.

Data Types in MicroPython

MicroPython supports the basic data types of Python, although with some limitations due to hardware constraints.

Next, we will look at the most common data types and how they are used.

Data TypeDescriptionExample
Integers (int)Whole numbers without decimals42
Floats (float)Numbers with decimals3.14
Strings (str)Sequences of characters"Hello, MicroPython"
Booleans (bool)Truth values (True or False)True / False

Integers (int)

Integers are whole numbers without a decimal part. In MicroPython, integers can be of arbitrary size. However, in practice, they are much more limited by the available memory (which is much less than on a PC).

integer = 42

Let’s look at the operations we can perform with integers.

a = 10
b = 3

sum = a + b       # 13
subtraction = a - b  # 7
multiplication = a * b  # 30
division = a / b   # 3.333... (in Python 3, division always returns a float)
integer_division = a // b  # 3 (integer division)
modulus = a % b     # 1 (remainder of the division)

Floating-point Numbers

Floating-point numbers are numbers with a decimal part. In MicroPython, floats are usually 32 bits (in Python, they are usually 64 bits), meaning they have limited precision.

floating = 3.14

The operations we can perform with floats are the usual ones 😆

a = 5.0
b = 2.0

sum = a + b       # 7.0
subtraction = a - b  # 3.0
multiplication = a * b  # 10.0
division = a / b   # 2.5

Strings

Strings are sequences of characters. Just like in Python, in MicroPython strings can be defined using single (') or double (") quotes.

string = "Hello, MicroPython"

Let’s review some common operations with strings.

greeting = "Hello"
name = "MicroPython"

message = greeting + ", " + name  # "Hello, MicroPython"
length = len(message)              # 16
substring = message[0:4]          # "Hell"

Booleans

Booleans are a data type that can only have two values: True (true) or False (false).

is_true = True
is_false = False

They are useful for expressing conditions and making decisions in the code. Common operations we can perform with booleans are,

a = True
b = False

logical_and = a and b  # False
logical_or = a or b    # True
logical_not = not a    # False

Collections

Another strong point of Python is its dynamic collections included by default. MicroPython incorporates almost all collections and features.

Let’s look at some of them.

Lists

Lists are ordered and mutable collections of elements. Both in Python and MicroPython, lists are one of the most beloved and widely used data structures due to their flexibility.

my_list = [1, 2, 3, 4, 5]

Some common operations with lists.

my_list = [1, 2, 3]

my_list.append(4)       # [1, 2, 3, 4]
my_list[0] = 10         # [10, 2, 3, 4]
length = len(my_list)   # 4

Tuples

Tuples are similar to lists, but they are immutable, meaning they cannot be modified after creation. They are useful for storing data that should not change.

my_tuple = (1, 2, 3)

Common operations with tuples are,

my_tuple = (1, 2, 3)

first_element = my_tuple[0]  # 1
length = len(my_tuple)        # 3

Dictionaries

Dictionaries are collections of key-value pairs. They are useful for storing and retrieving data efficiently using a unique key.

my_dictionary = {"key1": "value1", "key2": "value2"}

And finally, some common operations with dictionaries.

my_dictionary = {"name": "MicroPython", "version": 1.0}

value = my_dictionary["name"]  # "MicroPython"
my_dictionary["version"] = 1.1  # Updates the value
my_dictionary["new"] = "value"   # Adds a new key-value pair

That is, we basically have the same types as in Python. We just need to be aware that we have much less memory, so we cannot do as many “crazy things.”