Python: Libraries and Functions

What are functions?

A function is a set of instructions that can be executed from anywhere in your code. A function looks like a variable with a set of parentheses () at the end. They follow the same naming rules and conventions as variables. For example:

function()

do_something()

When we want Python to execute the instructions defined in a function, we call the function. The simplest way of calling a function is by typing its name, including the parentheses. For example, if we have a function called wait_ten() that makes Python pause for ten seconds, we can make Python perform this action like so:

y = 1 + 2 # y is set to 3

wait_ten() # Python waits for ten seconds

y = 5 # y is set to 5

wait_ten() is an example of a function that doesn't take any input, or produce any relevant output. It simply performs an action. These types of functions can be useful for long sets of instructions that are used repeatedly throughout a program. To make functions more flexible, however, we must introduce concepts of input and output.

Input and Output

Just like in math, a function can take some kind of input and produce some kind of output.

Input is used to determine the behavior of the function and/or the output it produces. To call a function with some particular input, we put the input in between the parentheses at the end of the function:

function(input)

Some functions can take more than one piece of data as input. Each piece of data passed into a function is called an argument. If a function takes more than one argument, we separate each one with a comma (,) For example, we might have a function called add_all() that takes multiple arguments, and adds them all together:

add_all(1, 2, 3) # 1, 2, and 3 are added together

All functions in Python return some kind of output. Similar to arithmetic expressions, the result of a function can be evaluated in the terminal, used to set variables, or even used as input to another function. Here are a few examples of how functions might be called:

sum = add_all(1, 2, 3) # a variable called "sum" is set to 6

print(add_all(4, 4)) # 8 is printed

add_all(2, 3, 4) # 2, 3, and 4 are added together, but the output isn't saved or used

A function can come from one of three different places.

  1. Built-in functions

Python has a number of functions directly built into it. These functions are always available and can be called from anywhere. Here are a few useful ones.

len()

The len() function takes a string of characters as an argument, and returns the length of the string as the output.

a = len('banana') # a = 6

b = len('a') # b = 1

c = len('') # c = 0

max()

The max() function takes two or more numbers as arguments and returns the largest one.

a = max(1,2,3) # a = 3

b = max(5) # b = 5

abs()

The abs() function takes a number as an argument and returns the absolute value.

a = abs(-12) # a = 12

b = abs(4) # b = 4

input()

The input() function doesn't take any arguments. Instead, it waits for the user to type something into the terminal and hit Enter. The output of this function is the string value of the user's input.

a = input() # waits for user input. when input is given, the string is stored in a

print()

That's right! print is a function too! print() takes any value as an argument and prints the results.

print("You already know this one!")

Practice: Functions Within Functions

Use built-in functions to calculate the maximum length of the two variables. Remember that functions can be used as input to other functions.

2. Functions from modules

A module is just a file of code that is stored somewhere outside of your script. Modules can contain variables and functions that you might want to use in your program. On your Metro board, modules are stored in the lib folder. To tell Python that we want to use some code from a particular module, we have to import it. Let's take another look at the blink code to see importing in action.

blink.py

import board

import digitalio

import time

led = digitalio.DigitalInOut(board.D13)

led.direction = digitalio.Direction.OUTPUT

while True:

led.value = True

time.sleep(2)

led.value = False

time.sleep(1)


Take a look at the first three lines. board , digitalio , and time are all modules! Notice that we import all three modules at the beginning of the file. It's best practice to do this so that Python has all of the tools it needs to properly run the rest of your code.

To access a function stored in a module we use a period. For example, look at the line

time.sleep(2)

Since we imported the time library at the beginning of the file, we can now access the function sleep(). This function takes a number as an argument and tells your microcontroller to do nothing for that many seconds.

Practice: Importing Modules

In this exercise, we use two different functions from the same module, but we forgot to import the module itself! Read the code to figure out which module we need, and import it at the beginning of the script.

# Note: numpy is a common python module that contains lots of mathematical functions

3. User-defined functions

We can write our own functions to use within our programs! This is the syntax for defining a function:

def <function-name>(x1, x2, ..., xn):

<function-body>

return <return-statement>

Let's break it down. The first line is called the function signature. This is where we tell Python that we are defining a function, what it's going to be called, and what arguments the function is going to take. The syntax has 4 components:

  1. The keyword def tells Python that we are going to define a function.

  2. Replace <function-name> with what we want the function to be called.

  3. (x1, x2, ..., xn) is called the parameter list. It can be completely empty or as long as you want. Each parameter in the list is like a variable that only exists within the function. When you call the function, you initialize these variables with the argument values passed into the function.

  4. The final piece of punctuation is a colon : , which tells Python that the signature is over, and we are about to start the function body.

The next lines make up the function body. This is where we put the instructions we want to execute when the function is called. The body can be as long or short as you want. Notice the indentation! The instructions that make up the function body must be indented. In Python, indentation is really important. You can either use a tab, or four spaces to indent. Either way, pick one and stick to it!

Finally, we have the keyword return . This is where we tell Python what we want the output of our function to be. The return statement can be a value, variable, or expression. This line also tells Python that the function definition has ended.

Examples:

Here are a few examples of function definitions:

def add_three(num1, num2, num3):

sum = num1 + num2 + num3

return sum


def print_two(message):

print(message)

print(message)

return


def times_four(number):

return (number * 4)

This function takes three arguments, adds them all together, and returns the sum.




This function takes one argument, prints it twice, and returns nothing




This function takes one argument, and returns the result of that argument times four.

Practice: Calling User-Written Functions