Part 3

Defining functions

We have already used functions such as len, print and input in our programs. These are functions built into Python, and so they are always ready at our disposal, no matter which environment we are programming in. However, it is also possible to define your own functions.

The function definition

Before a function can be used, it must be defined. Any function definition begins with the keyword def, short for define. Then comes the name of the function, followed by parentheses and a colon character. This is called the header of the function. After this, indented just like while and if blocks, comes the body of the function.

For example, the following code defines the function message:

def message():
    print("This is my very own function!")

If the program above is executed, nothing seems to happen. This is because the code in the body of the function is only executed when the function is called.

Calling a function is as simple as mentioning its name in your code. Adding a function call to the end of the above program, like so

def message():
    print("This is my very own function!")

message()

results in a printed statement:

Sample output

This is my very own function!

When a function has been defined it can be called multiple times:

def message():
    print("This is my very own function!")

message()
message()
message()
Sample output

This is my very own function! This is my very own function! This is my very own function!

Function arguments

Functions often take one or more arguments, which may affect what the function does. For example, the built-in Python functions print and input take as argument(s) the text that is to be displayed:

print("Hi!")                           # argument is the string "Hi!"
name = input("What is your name? ")    # argument is the string "What is your name? "
print(name)                            # argument is the value of the variable name

It was mentioned before that the terms argument and parameter are often used to refer to the same thing. The distinction is that while argument is used with the data passed to the function when the function is called, inside the function the arguments are assigned to variables called parameters. So, approximately, when the function is called, we call the passed bits of data arguments, but when we are defining the function, we call them parameters.

This may seem like a futile semantic distintion, and to make things even muddier, not all sources follow this definition. On this course we attempt to keep the distinction clear, however, as knowing the correct terminology will help you understand other sources besides this course material.

Let's define some functions that take arguments. In the function definition, the parameters are defined within the parentheses after the function name:

def hello(target):
    print("Hello", target)

Calling this function twice, like so

hello("Emily")
hello("world!")

prints out two different greetings:

Sample output

Hello Emily Hello world!

Let's take a closer look at the function definition:

def hello(target):
    print("Hello", target)

On the first line, in the function header, we defined that this function takes an argument, and assigns it to a parameter named target. In the body of the function the print command uses the value stored in target.

When the function is called, the parameter target has the value given as an argument in the function call. For example, the following function call

name = "Alan"
hello(name)

causes the parameter target to be set to the value "Alan".

The names of functions and their parameters follow the same principles as the names of variables. They should be descriptive, and contain primarily lowercase letters and underscore characters. Again, there are some exceptions to these guidelines, but we will ignore those for now.

More examples

Let's have a look at some more examples of functions which take arguments. In the following function definition the parameter is a number:

def squared(x):
    print(f"The square of the number {x} is {x * x}")

squared(2)
squared(5)
Sample output

The square of the number 2 is 4 The square of the number 5 is 25

Meanwhile, in this function definition there is an if statement within the body of the function:

def hello(name):
    if name == "Emily":
        print("Hello", name)
    else:
        print("Hi", name)

hello("Emily")
hello("Mark")
Sample output

Hello Emily Hi Mark

This function takes two arguments:

def sum(x, y):
    result = x + y
    print(f"The sum of the arguments {x} and {y} is {result}")

sum(1, 2)
sum(5, 24)
Sample output

The sum of the arguments 1 and 2 is 3 The sum of the arguments 5 and 24 is 29

The function also includes the helper variable result, which it uses to store the sum of its arguments.

Notice how the names of the parameters within the function definition have no relation to any variables outside it. We might just as well call the above function like this:

x = 100
y = 30
sum(1, 2)
sum(x + y, 10)

This should print out

Sample output

The sum of the arguments 1 and 2 is 3 The sum of the arguments 130 and 10 is 140

In the first function call the parameters are assigned the values x = 1 and y = 2. In the second function call they are assigned the values x = 130 and y = 10, regardless of the similarly named variables used in the function call.

We will come back to function definitions in the beginning of the next part of the course.

Warning: using global variables within functions

In the examples above we saw that it is possible to assign new variables within function definitions. The function can also see variables assigned outside it, in the main function. Such variables are called global variables.

Using global variables from within functions is usually a bad idea. Among other issues, doing so may cause bugs which are difficult to trace.

Below is an example of a function which uses a global variable "by mistake":

# this is a global variable
name = "Betty"

def hello(given_name):
    # using the global variable instead of the parameter by mistake
    print("Hello", name)

hello("Steve")
hello("Betty")
Sample output

Hello Betty Hello Betty

No matter how many different arguments we call the function with, it will always print out the value "Betty" stored in the global variable.

Please respond to a quick questionnaire on this week's materials.

Loading...
:
Loading...

Log in to view the quiz

You have reached the end of this section!

You can check your current points from the blue blob in the bottom-right corner of the page.