Fundamentals

Variables and Data Types

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

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 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 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 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
On this page