Introduction to Functions
The power of modularity.
You may be familiar with the concept of functions from mathematics. If you'll forgive me invoking some traumatic high school memories, you may remember functions looking like this:
Functions in computer science follow the same principle: they expect some inputs, and return some output. This same function in Python looks like this:
return 2**x - x**4
Functions in programs defer from mathematical functions in one critical way — they can produce side-effects. Let's make a small edit to the previous function:
return 2**x - x**4
fis essentially the same as the mathematical f — it takes an input x and computes and returns a value based on that input. However, this function also prints "Hi!" every time a value is computed — the output isn't changed, but the function's behavior is. This is a side-effect.
At this point, you may be starting to develop an idea about what a function typically looks like. Let's give certain parts of functions certain keywords, to make it easier for us to talk about them later.
Given a function
def f(x, y=1):
a = x * y
The name of this function is
f, and it is said to accept 2 arguments
y. When no value is passed in for
y, it is automatically set to 1 — this is known as the argument's default value. The entire first line together is known as the "function signature". Everything that is tabbed inside of a function is known as the "body" of the function.
This function would be called like so:
This would return to us a value 2 * 3 = 6. Similarly, a function call like the following:
would return the value 2 * 1 (default of
y) = 2.
Now that we've spent a bit of time developing an understanding of programming functions, one has to wonder: what is the point of functions? Why have functions in a programming language anyway?
The idea behind functions is to encourage modularity. A function can be thought of as a black box, that accepts some inputs and splits out some output based on some rules. Once written, you and I shouldn't have to worry about how that function works.
This is the contract between a function and its caller — if valid inputs are provided, expected outputs are returned. This is also what makes functions one of the most powerful building blocks in all of computer science.