A function groups a reusable block of instructions under a name. Rather than copying the same blink sequence ten times over, you write it once inside a function and call it. It is the basic tool for factoring out (not repeating yourself) and for naming (making the code readable). In MicroPython a function is declared with def, without stating the type of its arguments. See also the general notion of a function.

Declaring and calling

def saluer():
    print("Hello from the Pico")
 
saluer()        # call -> displays the message

def opens the definition. The body is indented, and the call is made with nom(). The definition has to be executed before the call, so it is written higher up in the file.

Arguments and default values

A function takes arguments in brackets. You can give a default value, used when the argument is left out:

from time import sleep
 
def clignote(led, n=3, duree=0.2):
    for i in range(n):
        led.on()
        sleep(duree)
        led.off()
        sleep(duree)
 
clignote(led)            # 3 blinks of 0.2 s (default values)
clignote(led, 5)         # 5 blinks
clignote(led, 10, 0.05)  # 10 fast blinks

Returning a result

return hands a value back to the caller. With no return, the function returns None.

def lire_tension(adc):
    brut = adc.read_u16()        # 0..65535
    return brut * 3.3 / 65535    # conversion into volts
 
v = lire_tension(capteur)
print("Voltage:", v, "V")

A function can even return several values at once (as a tuple): return mini, maxi, picked up with a, b = ....

Pitfalls

Forgetting return. A function that is meant to supply a value but has no return returns None, so v = lire_tension(capteur) would give None and the next calculation would fail. Check that you really are returning the result.

Calling before defining. The def line has to have been executed before the call. Define the functions at the top of the file, and call them afterwards.

Internal variables are invisible outside. A variable created inside a function is local, so it does not exist outside it. To share a value, return it rather than relying on a global variable (the notion of scope, see local and global scope).

Exercises

Exercise 1 — A blink function you can tune

Write a function clignote(led, n) that blinks a LED n times (0.2 s on / 0.2 s off), then call it for 4 blinks.

Exercise 2 — Convert an ADC reading

Write a function en_volts(brut) that converts a raw reading (0–65535) into a voltage (3.3 V reference) and returns the result. Test it with brut = 32768.

See also