Functions

MPDA’22

December 23, 2021

What is a function?

A function is a block of code which only runs when it is called.

Calling a function just means to use a function in your code.

We’ve been using funcions during the entire course:

range(3,9)
math.cos(2*math.pi)
math.sin(math.pi)
abs(-1)
ptA.DistanceTo(ptB)
interval.ParamterAt(0)
curve.ClosestPoint(ptA)
cross = rg.Vector3d.CrossProduct(...)
surf = rg.Surface.CreateByCorners(...)

You can pass data, known as parameters, into a function.

A function can return data as a result.

Creating a function

You can create a function by using the def keyword, followed by the name and the (optional) inputs surrounded by parenthesis.

def myFunction():
    print("Hello from inside myFunction!")

Inside the indented block you can add any code you wish.

And use it like this:

myFunction()

A function can optionally have input parameters (variables)

These parameters can be of any type.

def addNumbers(a,b):
    addition = a + b
    print(addition)

# And use it placing the values inside the parenthesis
addNumbers(4, 2.3)

A function can also return data

def addNumbers(a,b):
    addition = a + b
    return addition

result = addNumbers(3,44)
print(result)

The return value can be saved into a variable for later use.

Why should you use them?

Functions are useful in many ways:

  • to abstract the logic into understandable pieces.
  • to re-use code in multiple parts of your application.
  • to simplify the logic of your application

Essentially, a python function is the equivalent of a grasshopper node:

  • They each have independent inputs that can vary
  • They each perform a specific operation, and have a descriptive name.

There’s only one main difference between them:

A python function can only have one return value

What does having only one return value? even mean?

It means that the result of any function has to be a single item (or no item at all).

If you need to output more than one item, you can output a list/tupple or dictionary that collects the multiple items you want to send.

def multipleOutput():
    return ["a", "b", "c"]

Recursivity

What is recursivity?

According to wikipedia, recursive is something that involves the repeated application of a rule, definition, or procedure to successive results.

🤔 🤔 🤔

In other words:

Recursive is any operation that you repeat over and over using the result from the previous iteration.

In programming, a function is recursive if it calls itself.

def power(num, exp):
    if(exp >= 1):
        return num
    return num  * power(num, exp - 1)
def countdown(start):
    if(start != 0):
        print(start)
        countdown(start - 1)
    else:
        print("BOOM!")

Meaning, that inside the function’s code you are using the same function you are creating.

References

Generic resources

  1. Generic python
  2. Codility Code Challenges
  3. Rhino Developer Docs
  4. RhinoCommon API
  5. Python for Non-Programmers

Rhino/GH resources