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...

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

Some common operations with lists.

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

Tuples are similar to lists, but they are immutable...

my_tuple = (1, 2, 3)

Common operations:

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

Dictionaries are collections of key-value pairs...

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

Common operations:

my_dictionary = {"name": "MicroPython", "version": 1.0}
value = my_dictionary["name"]
my_dictionary["version"] = 1.1
my_dictionary["new"] = "value"