Learn Programming with Python — Introduction to Functions

Posted on April 29, 2020 in Learn Python

Learn Programming with Python — Introduction to Functions

Functions are the life-blood of many Python programs. Let’s learn all about them in this instalment!

Photo by Christina Morillo — https://www.pexels.com/@divinetechygirl

Learn Programming with Python — Introduction to Functions

Functions are the life-blood of many Python programs. Let’s learn all about them in this instalment!

In the introduction to this series we used two of Python’s in-built functions: print() and input() . The first was used to output information to the terminal. The second was used to get input from the terminal. In this instalment we’ll learn more about Python’s in-built functions. We’ll also be creating our own functions to do things no-one else has thought about!

What is a Function, Anyway?

Head over to Wikipedia to read about the mathematical definition of “function” first, then come back here to read my simplification!

OK, here goes. A function performs a specific operation on its arguments and produces a predictable output. Huh, not much simpler, and definitely not as precise (or as correct) as the other definition. Let me give you an example of an automated teller (ATM) machine which provides money (if your bank approves!).

The ATM has a function which gives you money based on a bunch of different inputs: (your card, your pin number, the amount of cash requested, the availability of cash in the machine, and whether or not your bank approves of the withdrawal). The ATM is quite a bit more complicated than this, but I only needed a quick example and this will do fine. Every time you use the ATM to withdraw cash, you are using the same function. If the inputs remain the same then the output will be predictably the same: cash (if everything is fine) and no cash (if the machine is empty, for example). If the ATM behaved randomly it would be of no use at all.

We could say that finding the product of two numbers is a function. A python function which accepts two numbers as input arguments, multiplies them, then returns the product as the output is a function.

Let’s Code!

I created a new file in VS Code called product.py, and entered the following text:

def product(a, b):
    return a * b
print (product (2, 7))

After executing this program, in the terminal the output of 14 is shown.

A user-defined function.

Let’s dissect this simple function.

  • We start by defining a function using the Python keyword def which indicates that a new function definition will immediately follow.
  • Then we provide the name of the function: product .
  • Next we specify that this function accepts two arguments: a, b
  • Then we begin the function’s body on line 2, using an indent of four spaces. Python uses indents a lot. Save yourself future headaches by using the four spaces, or setting your editor to convert tab characters to four spaces. The Python community has defined this and other conventions in the guide PEP-8.
  • The body defines a variable called calculation and assigns the product of a * b to it.
  • The body uses the keyword return to indicate that it exits at this point, returning the value of the variable calculation back to the code which called the function.
  • The return value is given as a * b . The two arguments are multiplied together to create the product.
  • The function returns the product to the caller, where it is stored in the answer variable we created just for this value.

The function itself is not actually executed until line 5, when we invoke (or call) the function:

answer = product (2, 7)

The return value of the function named product is assigned to the variable named answer. The final line simply prints the answer to the terminal.

At this point I should mention that, in Python, it is really important that the function is known about before it is called. That’s why the function appears first in this file, and is called last.

This is a lot of steps, but it can be simplified. We created two variables to hold values between steps: calculation and answer. We don’t really need to store intermediate values, we could have been more direct. In the following screenshot, you can see that I am directly returning the result of a * b, and also directly calling the product() function from within the print() function. Programmers often make choices about how to write their code, with two different styles — like here — producing the same results. One style is more readable, one uses fewer resources.

A user-defined pront() Function!

From the previous post, you may recall that I was able to introduce a bug — a syntax error — by misspelling the print() function to pront() — which doesn’t exist. Now, let’s create that pront() function! It has the job of both requesting an input and producing an output, in a single function.

Here it is, in the truncated and terse style:

And here is a longer version, in the more verbose style:

And this is how it looks in VS Code.

Keyword and Positional Arguments

In our previous example, I used two arguments to the pront() function. The first argument was for the input prompt, the second argument gave the welcome message. These arguments are positional. If I reversed them, the result would be backward. Try it yourself by invoking the pront() function with this code:

pront ("Hello,", "Please enter your name: ")

Wouldn’t it be nice if we could name each argument individually, so that we could use the names in any order? We can! Python allows us to use either positional or keyword arguments. It’s possible to mix and match, but that would get too complicated for now. Our arguments already have the names prompt and message, we can invoke the function using these names explicitly, in any order.

pront (message="Hello,", prompt="Please enter your name: ")

And it now works as intended.

Use of argument names as keywords

Return Values from User-Defined Functions

In our first example in this post, we used the return keyword to return a value to the function’s caller. But in the second example, pront() we did not use return to return a value. Why? The author of a function can choose how the function returns, as a matter of their programming style.

  • Always returning a single value is considered good style by many. Functions which don’t return a value, or return multiple values are harder to use. They’re not behaving like most functions.
  • Not returning a value sometimes makes sense for fire-and-forget functions where you want the function to take care of everything.
  • It is possible to return multiple values in Python, which can make sense in some scenarios, explained below.

Multiple Return Values from a User-Defined Function

When does it make sense to return more than one value from a function? It is a matter of judgement. The location of a point on the Earth’s surface can be expressed with two values, the latitude (degrees North or South) and the longitude (degrees East or West) of the point. In decimal notation, the location of the Eiffel tower is (48.858093, 2.294694) for latitude and longitude.

Let’s define a function geolocation which can return the hard-coded geolocation of three landmarks: the Eiffel Tower, the Statue of Liberty or the Sydney Opera House.

Geolocation function.

This function introduces a new concept (if, elif, else) which we’ll cover soon. I’m smuggling it in here for now. The interesting thing, for now, is that the return statements are returning two values: the latitude and the longitude as a single result.

This single result is a compound data type which itself is comprised of multiple parts. This is called a tuple. In the real world, the geolocation of an object is a compound of two parts: the latitude and the longitude. A person’s legal name is also often a compound data type comprising of the person’s first name and their last name: (“Richard, “Quinn”) for an eponymous example!

When we return multiple values from a python function, what we’re really saying is “I am returning a compound value comprising multiple parts — a tuple”.

What Have We Achieved?

Congratulations, you’ve reached the end of this article “Learn Programming with Python — Introduction to Functions”. Here’s what we’ve done so far:

  • Discussed what a function in a computer program is.
  • Created a function using the def keyword.
  • Passed values to the function as arguments.
  • Considered specifying the arguments using keywords when calling the function.
  • Discussed returning zero, one or multiple values from the function back to the caller.

Although we’ve covered a lot of ground here, there are quite a few more specifics to cover in the topic of functions. We’ll leave those for a future instalment. Our next instalment will get to grips with controlling the flow of execution in a program, where we’ll return to that if … elif … else construct shown earlier.

Articles in this series so far: