logo

Ziffur

Functions: How to Simplify, Reuse, and Expand your Code

Functions: How to Simplify, Reuse, and Expand your Code

20 July 2021

This article assumes that you know some basic concepts in computer science as well as how to read code written in Python. If you've read and understood the previous article in this series, you're good to go. If you're not so confident, feel free to check out some of the previous articles to catch up. Moving on!

Writing code to accomplish simple tasks (like counting to five) is cool and all, but that's not what we call "real software", is it? That depends. Regardless of what various experts in the field will tell you, a piece of software is only as good as the real-world problem it solves. This means that a simple, hacky script written to rearrange files in a folder may provide more benefit to its users than an elaborate, elegant system designed to count blades of grass in a live video feed. Still, even though we don't need to write beautiful, correct code to solve real-world problems, we can still try.

Functions

Adding to the box of basic tools we reach for first, let's talk about functions. A function is used to wrap a section of code with a specific functionality. This achieves two things: First, we can call the function to invoke its effect at any point in our script, allowing for easy reuse. Second, we can name the function, abstracting away its implementation and emphasizing its effect instead. Take the following example:

def sayHello():
    print('Hello!')

sayHello()
# Hello!

sayHello()
# Hello!

for i in range(3):
    sayHello()
# Hello!
# Hello!
# Hello!

Here we see how functions are defined using the def keyword followed by a name and a pair of parentheses. The function's body is then contained within a code block starting with a colon (:) and an indentation of (usually) four spaces. After defining the function sayHello, we call it using the syntax sayHello(), which executes the code in the function's body. This function is very predictable (and quite boring) since it takes no input. Let's find out how to improve it.

Function Parameters

Notice how we call the sayHello function by putting a set of parentheses behind it. This looks a little odd at first glance but there's an important reason behind it. Within these parentheses we can add function parameters which influence the behavior of the function. We can see this in the built-in print function above, which prints its parameters to the Python console. This shows how a function's parameters can directly influence its output.

Let's redefine the sayHello function and add a parameter to it. We'll name this parameter person and use it to build the message.

def sayHello(person):
    print('Hello ' + person)

sayHello('Alice')
# Hello Alice

sayHello('Bob')
# Hello Bob

Now that sayHello takes the parameter person, this parameter is required when we call the function. If we call it with no parameters as before, sayHello(), we will receive the following error message:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: sayHello() missing 1 required positional argument: 'person'

We can make this parameter optional by giving it a default value like so:

def sayHello(person = 'Stranger'):
    print('Hello ' + person)

sayHello()
# Hello Stranger

sayHello('Alice')
# Hello Alice

A function can also take multiple parameters separated by commas. We'll show an example of this in the next section.

Return Values

So far, our functions have only produced outputs to the Python console and not into the rest of our code. This is known as a side effect. Side effects in functions make them impure in mathematical terms but are often necessary for user interaction and feedback. The mathematically pure way for a function to deliver its output is to use return values. This allows us to pass the output on to the rest of the code where we can do more with it. Let's have a simple example:

def concatenate(a, b):
    return a + ' and ' + b

people = concatenate('Alice', 'Bob')
print(people)
# Alice and Bob

sayHello(people)
# Hello Alice and Bob

more_people = concatenate(people, 'Charlie')
sayHello(more_people)
# Hello Alice and Bob and Charlie

Here we create a variable people which stores the output returned by the add function. This allows us to continue using it to influence the rest of our code, such as by passing it to the sayHello function or using it to compute new variables.

Functions are the last basic tool we need to start building code with real-life benefits. In the next article, we'll write a Python script which simulates a simple card game and prints out the results.

Tags

Computer Science
Programming