Unit 5 - Functions

Functions are such a huge part of programming that we will be spending two weeks (weeks 5 and 7) on this subject.

In this unit we will be discussing:

  • What a function is
  • Why do we use functions
  • Arguments vs Parameters
  • Return Values
  • Variable Scope
  • Passing by Assignment

A function consists of three parts:

  1. The input(s) to the function
  2. The function itself
  3. The output from the function

You can think of a function as a machine (black box) that takes some input(s), does something, and then produces an output.

Once you define a function, you can reuse it. This is the principal reason for their existence. Don't Repeat Yourself! (DRY)

I have included 5 examples of functions. For now, I want you to understand the idea as a concept. We will see examples 1, 2, 4, and 5 in Python very soon!

1. Example Function - Is a Number Odd?

The first function takes in 1 input (an int) and produces 1 output (a bool).

This function is a machine that tells us whether the input is odd.

For now, we don't care how it works, we just assume it does.

The following image depicts the function on the left and then two examples of it being used on the right.

Odd Function Example

2. Example Function - Add Two Numbers

The second function takes two inputs which are numbers (float) and outputs the sum of those two numbers.

Key point, a function can take multiple inputs!

Add Function Example

3. Example Function - What Colour is a Shape?

The third function might look odd as in python we do not have a Shape type (yet!). Later in the course, we will make one.

It serves to demonstrate that a function is just a machine that does something to the input and produces an output.

Colour Function Example

4. Example Function: Print Hello Name

The final two examples are quite common. The first has an input, but no output. It takes in a person's name (e.g "Emily") and prints "Hello Emily" to the terminal.

We will talk about this and its relationship to Python's None.

Colour Function Example

5. Example Function: Print Hello World

The final example has no input and no output. It is just a machine that runs a piece of code.

In this case, it just prints "Hello World".

Colour Function Example