funciones-en-micropython

How to Use Functions in MicroPython

  • 4 min

In this tutorial, we will see what functions are and how to use them in MicroPython, and how we can use them to make our code cleaner and more modular.

A function is a block of code that performs a specific task and can be called (or invoked) from anywhere in a program.

This allows us to break a problem into smaller parts, as well as avoiding the need to repeat the same code in multiple places.

Functions are a basic feature of Python (just like in many other languages). Of course, MicroPython incorporates the same syntax and functionality.

Basic Syntax of a Function in MicroPython

In MicroPython, functions are defined using the keyword def. The basic syntax is as follows:

def function_name(parameter1, parameter2, ...):
    # Code that performs the task
    return result
  • def: Indicates that we are defining a function.
  • function_name: Is the name we give to the function.
  • parameter1, parameter2, …: Are the values that the function receives as input. They can be optional.
  • return: Specifies the value that the function returns as a result. It is not mandatory, but it is common in functions that perform calculations or transformations.

It is highly advisable that the function name is descriptive and clearly indicates the task it will perform.

Let’s look at each of the components of the definition with some examples,

Simple Function Without Parameters

Let’s start with a simple example. Suppose we want to create a function that prints “Hello, world!” to the console.

def greet():
    print("Hello, world!")

# Call the function
greet()

Output:

Hello, world!

In this case, the function greet does not receive parameters and does not return any value. It simply executes the code it contains when called.

Function with Parameters

Now, let’s create a function that receives a parameter and uses it in its logic. For example, a function that greets a person by name.

def greet_person(name):
    print(f"Hello, {name}!")

# Call the function
greet_person("Juan")
greet_person("Ana")

Output:

Hello, Juan!
Hello, Ana!

Here, the function greet_person receives a parameter called name and uses it to personalize the message.

Function with Return Value

Functions can also return values using the keyword return. This is useful when we want the function to perform a calculation and return the result.

def add(a, b):
    result = a + b
    return result

# Call the function and store the result
total = add(5, 3)
print(f"The sum is: {total}")

Output:

The sum is: 8

In this example, the function add receives two parameters (a and b), performs the addition, and returns the result. Then, we store that result in the variable total and print it.

Lambda Functions (Anonymous)

Lambda functions are a very convenient syntax for defining anonymous functions in a single line. They are useful for small functions and simple operations.

square = lambda x: x ** 2
print(square(4))  # Output: 16

Functions Within Functions

In MicroPython, we can also define functions within other functions. This is known as nested functions and is useful when we want to encapsulate logic that is only relevant within a specific context.

def calculate_tax(price):
    def apply_vat(price):
        return price * 1.21  # VAT of 21%
    
    price_with_vat = apply_vat(price)
    return price_with_vat

# Call the function
total = calculate_tax(100)
print(f"Price with VAT: {total}")

Which would output,

Price with VAT: 121.0

Here, the function apply_vat is defined within calculate_tax and is only accessible within the latter.

Just because you can do it doesn’t mean you should abuse it.

Practical Examples