Functions in MicroPython on Raspberry Pi Pico

Posted

in

by

Functions are a way to make your code more organized and easier to understand. They are like little machines that you can use over and over again in your code.

To create a function, you need to give it a name and then write what it does. You can also give it some inputs, like numbers or strings, that it will use to do its job.

For example, imagine you wanted to make a function that adds two numbers together. You could call it “add” and write the code like this:

def add(num1, num2):
    result = num1 + num2
    return result

Now, whenever you want to add two numbers together, you can just call the “add” function and give it the two numbers you want to add:

result = add(5, 7)

The “add” function will take those two numbers, add them together, and then return the result, which you can store in a variable called “result”.

Functions are really helpful because they can make your code shorter, easier to read, and easier to test.

Examples to try

Here are some more examples of functions in MicroPython on Raspberry Pi Pico:

Example 1: Adding Two Numbers

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

# Test the function
print(add_numbers(2, 3)) # Output: 5
print(add_numbers(5, 10)) # Output: 15

Example 2: Counting Even Numbers

def count_even_numbers(numbers):
    count = 0
    for num in numbers:
        if num % 2 == 0:
            count += 1
    return count

# Test the function
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(count_even_numbers(numbers)) # Output: 5

Example 3: Finding the Maximum Number in a List

def find_max(numbers):
    max_num = numbers[0]
    for num in numbers:
        if num > max_num:
            max_num = num
    return max_num

# Test the function
numbers = [3, 9, 2, 5, 1, 8, 4, 7, 6]
print(find_max(numbers)) # Output: 9

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *