This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Custom functions

Function definitions

face Josiah Wang

Let’s explore function definitions in more detail.

1
2
3
4
5
6
7
def absolute_value(number):
    if number < 0:
        new_number = -number
    else:
        new_number = number

    return new_number

In line 1, def is a keyword to indicate that this block of code is a function definition.

You also give the name of your function (absolute_value), and define any input parameters (number).

The parameter is just a variable. At this point, you do not know the value of number (nor do you need to know it). It is just a variable at this point. This is only assigned when you call the function from your program with an input argument (e.g. absolute_value(-34)). This is an example of abstraction in action - the value of number can change whenever a function is called.

Note the difference between the terms parameters and arguments.

  • Parameters are possible input variables that a function can take (what can you give as input?)
  • Arguments are concrete objects that you provide when you run your program (what is the value of the input?)

Parameters vs. Arguments

You then have the body of your function definition that does all your computation (lines 2-5). This is basically like any program that you have written so far.

Finally, once you are done with your computation, you can return the value of your output to your caller with a return statement. In this case, it returns the object that new_number refers to.

If you do not include a return statement, the function will automatically return None.

You do not have to wait till the end of the function definition to return your value. You can return a value at any point in the program. For example, the following code is valid. Once any return statement is reached, then the function call stops, and the output is returned to the caller.

1
2
3
4
def absolute_value(number):
    if number < 0:
        return -number
    return number