Functions

In the world of design, planning and repetition are key. We often find ourselves repeating similar tasks. In Python, we can simplify these repetitive tasks using something called a function.


What is a Function?


Think of a function as a blueprint for a timber structure. This blueprint is a set of instructions that tells us how to build a particular structure. Similarly, a function in Python is a set of instructions that performs a specific task. Just like how we can use the same blueprint to build multiple structures, we can use the same function to perform the same task multiple times.

Creating a Function


Let’s consider a simple task: calculating the volume of a timber beam. In Python, we can create a function to do this for us.

def calculate_beam_volume(length, width, height):
  volume = length * width * height
  return volume


In this example:


Calling a Function


Now that we have created our function, we can call it to perform the calculation. To do this, we simply write the name of the function followed by the values we want to feed into it.

calculate_beam_volume(10, 20, 30)


The return value can be stored in a variable.

beam_volume = calculate_beam_volume(10, 20, 30)
print(beam_volume)


This will output the 1.0, the volume of the beam.



Why Do We Need Functions?


Functions in Python, like blueprints in architecture, allow us to simplify complex tasks and repeat them easily and accurately. They are a powerful tool in any Python programmer’s toolkit:

As you can see we can actually call the same function twice but with different parameters.


By using functions it can be reworked to be much more organized and readable like so:

def func_a():
  ### line of code 1
  ### line of code 2
  ### line of code 3
  ### ...

def func_b():
  ### line of code 16
  ### line of code 17
  ### line of code 18
  ### ...

def func_c():
  ### line of code 36
  ### line of code 37
  ### line of code 38
  ### ...

def func_abc():
  func_a()
  func_b()
  func_c()

func_abc()  # <-- this is the called function


🛠 Exercises


01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍

Solutions:

01: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 02: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍 03: 🐍⬇️⬇️⬇️ Download the script here ⬇️⬇️⬇️🐍