def add_numbers(num1, num2):
""" Adds two input numbers together. """
= num1 + num2
result return result
4 Functions
After learning how to use other people’s functions, it’s time to write our own! We will look at the anatomy of how a function is constructed, and see bunch of examples in action.
First, we remind ourselves why we write functions in the first place. We write functions for two main, often overlapping, reasons:
Following DRY (Don’t Repeat Yourself) principle: If you find yourself repeating similar patterns of code, you should write a function that executes that pattern. This saves time and the risk of mistakes.
Create modular structure and abstraction: Having all of your code in one place becomes increasingly complicated as your program grows. Think of the function as a mini-program that can perform without the rest of the program. Organizing your code by functions gives modular structure, as well as abstraction: you only need to know the function name, inputs, and output to use it and don’t have to worry how it works.
Some advice on writing functions:
Code that has a well-defined set of inputs and outputs make a good function.
A function should do only one, well-defined task.
4.1 Anatomy of a function definition
This is how you define a function:
def <function name>(<input arguments>):
""" documentation string """
code block
return <variable>
<function name>
is the function’s name you are creating.<input arguments>
specify the input arguments for the function as variable, separated by commas.""" documentation string """
describes what the function is doing. It is considered optional but highly recommended.code block
performs the action of the function, typically using the input arguments of the function.return <variable>
it the output of the function.
Here’s an simple example to define a function that adds two numbers together:
When this code is run, add_numbers()
is stored in the environment, but the function is never run. To run the function,
3, 4) add_numbers(
7
When the function is called, the input values 3 and 4 are reassigned to function input arguments num1
and num2
to be used within the function.
We need to introduce the concept of local and global environments to distinguish variables used only for a function from variables used for the entire program.
4.2 Local and global environments
Within a function, all input arguments and any new variables defined are stored in a “local environment”, and is only accessible within the function’s body. The overall environment of the program is called the “global environment” and can be also accessed within the function.
The reason of having some of this “privacy” in the local environment is to make functions modular - they are independent little tools that should not interact with the rest of the global environment. Imagine you writing a function that you want to give someone else to use, but your function depends on your global environment - it would not be portable!
To illustrate the distinction between a the local and global environment, the following tool allows you to step through Python code execution line-by-line and see the relationship between order of execution, variables, and environments. The “Global frame” refers to the global environment, and “add_numbers” refer to the local environment for the function add_numbers()
.
If it doesn’t load properly, here is the link.
4.3 Function arguments create modularity
First time writers of functions might ask: why are variables we use for the arguments of a function reassigned for function arguments in the local environment? Here is an example when that process is skipped - what are the consequences?
= 3
x = 4
y def add_numbers(num1, num2):
""" Adds two input numbers together. """
= x + y
result return result
Let’s try this function out for a few values:
add_numbers(x, y)
7
10, -5) add_numbers(
7
Why is this happening? Let’s try to step through this interactively:
If it doesn’t load properly, here is the link.
The function did not work as expected because we used hard-coded variables (x
, y
) from the global environment and not function argument variables unique to the function use!
4.4 In-Class Exercises
Write a function,
my_abs(x)
that computes the absolute value of an input numeric value and returns it. Use cases:my_abs(-3) = 3
,my_abs(0) = 0
,my_abs(33) = 33
. You will need to use conditional statements within the body of the function.Write a function,
my_abs_iterated(x)
that takes in a list of numerical values and usemy_abs(x)
to take the absolute value of each element. Use cases:my_abs_itereated([3, -9, 2]) = [3, -9, 2]
.
4.5 Exercises
Exercise for week 4 can be found here.