colidescope

/guides/ functions

Welcome! You are not currently logged in. You can Log in or Sign up for an account.

Functions

Functions are a critical tool in computer programming which allow you to package sections of code making the logic much more reuseable throughout our code

+Introduction

In this module, we will learn how to package sections of code in custom Functions so it is easily reusable throughout our code.

So far, we have seen how we can use Variables in Python to store different kinds of data and how we can use the 'flow control' structures Conditionals and Loops to change the order or the way in which lines of code get executed.

With only these tools we can already start to express some pretty complex logics. However, with only our current tools, any sufficiently complex script would start to get very long, since every time we wanted to do a certain process we would have to rewrite all of its code within our script (probably by copying the code and pasting it wherever it was needed in our script).

Even worse, the code would become extremely hard to manage since any change to the logic would have to be manually updated everywhere it was implemented. This process would not only be time consuming but would introduce potential bugs from human error.

This is where Functions come in. Functions allow us to 'wrap' sections of code representing a specific functionality while exposing a set of inputs the control that functionality and a set of outputs it produces. This is similar to how components work in Grasshopper, but implemented with code.

Implementing a Function makes the logic implemented in the Function's code easily reuseable anywhere it's needed in the rest of our program. It also allows for much easier management of changes since the change only needs to be done once (in the Function's code) and it will automatically update wherever the Function is called.

+Working with Functions

We have already seen and used some Functions such as type(), str(), and range() which are included with Python. But what are Functions really?

As in math, a Function is a basic structure that can accept inputs, perform some processing on those inputs, and give back a result. Let's create a basic Function that will add two to a given number and give us back the result:

def add_function(input_number):
    result = input_number + 2
    return result

A Function's definition begins with the keyword def. After this is the Function's name, which follows the same naming conventions as Variables. The Function's name is always followed immediately by a set of parenthesis. Inside the parenthesis you can place any number of input variables separated by commas (,), which will be passed to the Function when it is called, and are available within the body of the Function. If a Function does not expect any inputs you still include the parenthesis, however in this case there won't be anything inside of them, for example: my_function_name().

On its own, this code will only define what the Function does, but will not actually run any code. To execute the code inside the Function you have to call it somewhere within the script and pass it the proper inputs:

print(add_function(2))

Here we call the Function by writing its name and passing in '2' as the input. The result of the Function (the number '4') will then be passed into the print() Function which will print '4' to the console.

When you call a Function, you can either directly pass values or pass Variables that have values stored inside of them. For example, this code will call the Function in the same way:

var = 2
print(add_function(var))

Here the value of the var variable, which in this case is 2, is being passed to the add_function Function, and is then available within that Function through the input_number Variable. Notice that the names of the two Variables var and input_number don't have to match. When a value gets passed to a Function it is reassigned to the Variable name declared in the Function definition, and the value is then available through that name.

In this case we refer to var as a global variable since it stores the value '2' in the main script, while input_number is a local variable since it stores that value only within the body of that Function. In this way, Functions 'encapsulate' specific tasks along with all the data that is necessary to execute that task to limit the number of global variables necessary within the main script.

The first line declaring the Function and its inputs ends with a colon (:), which should be familiar by now, with the rest of the Function body inset from the first line. Optionally, if you want to return a value from the Function back to the main script, you can end the Function with the keyword return, followed by the value or variable you want to return. Once the Function hits on a return statement, it will skip over the rest of the body and return the associated value. This can be used to create more complex behavior within the Function:

def add_function(input_number):
    if input_number < 0:
        return 'Number must be positive!'
    result = input_number + 2
    return result

print(add_function(-2))
print(add_function(2))

You can see that in this case, if the input is less than zero the Conditional will be met, which causes the first return statement to run, skipping the rest of the code in the Function. However, if the number is equal to or greater than zero, the Conditional will be skipped causing the rest of the Function to run, ending with the second return statement.

You can pass any number of inputs into a Function, but the number of inputs must always match between what is defined in the Function and what is passed into it when the Function is called. For example, we can expand our simple addition Function to accept two numbers to be added:

def add_two_numbers(input_number_1, input_number_2):
    result = input_number_1 + input_number_2
    return result

print(add_two_numbers(2, 3))

You can also return multiple values by separating them with a comma (,) after the return statement. In this case, you also need to provide the same number of variables to which to assign the results of executing the Function. Let's expand our Function to return both the addition and multiplication of two numbers:

def two_numbers(input_number_1, input_number_2):
    addition = input_number_1 + input_number_2
    multiplication = input_number_1 * input_number_2
    return addition, multiplication

val_1, val_2 = twoNumbers(2, 3)
print('addition: ' + str(val_1))
print('multiplication: ' + str(val_2))

Functions are extremely useful for creating efficient, manageable, and legible code. Wrapping up sections of code into custom Functions allow you (and possibly others) to reuse code in a very efficient way, and also forces you to be explicit about the set of operations involved in accomplishing a certain task in your code, as well as the data needed execute it.

You can see that the basic definition of Functions is quite simple, however you can quickly start to define more advanced logics, where Functions call each other and pass around inputs and returns in highly complex ways. You can even pass a Function as an input into another Function and create Functions which call themselves. These are called Recursive Functions which we will look at in a later guide.

+Exercise: Attractor Points—Part 3

In this guide we've seen how functions can be used to wrap sections of code that define specific functionality to make it much easier to reuse throughout our code. The following exercise will give you hands on experience with writing and using functions by applying them to the attractor point example developed in the previous exercise. If you don't have it handy you can download the definition from the previous exercise here:

⚠️
⚠️
You need a premium account to access this content.
exercise-attractor-point-part-3-start.zip
Starting model

+CHALLENGE 7: Two attractors

Can you modify the definition to work with two attractor points instead of one?

grasshopper setup

HINT: Start by creating an additional point in Rhino and referencing it into the Grasshopper definition. Then input the new point into the Python component and use it's distance to each point along with that of the first point to calculate the final radius of each Circle. You can try a variety of ways to combine the effect of both attractors, for example adding the two distances together, or taking the minimum of the two distances using Python's built-in min() Function.