funciones-en-micropython

How to Use Functions in MicroPython

  • 4 min

In this tutorial, we are going to 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 down a problem into smaller parts, and also prevents us from having to repeat the same code in multiple places.

Functions are a basic feature of Python (as 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
Copied!
  • def: Indicates that we are defining a function.
  • function_name: This is the name we give to the function.
  • parameter1, parameter2, …: These are the values the function receives as input. They can be optional.
  • return: Specifies the value 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()
Copied!

Output:

Hello, world!
Copied!

In this case, the greet function receives no parameters and returns no 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 their name.

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

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

Output:

Hello, Juan!
Hello, Ana!
Copied!

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

Function With Return Value

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

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}")
Copied!

Output:

The sum is: 8
Copied!

In this example, the add function 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 (Anonymous) Functions

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
Copied!

Functions Inside Functions

In MicroPython, we can also define functions inside 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}")
Copied!

Which would output:

Price with VAT: 121.0
Copied!

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

Just because you can do it doesn’t mean you should overuse it

Practical Examples