Previous Lesson Table of Contents Next Lesson

You may recall that the formula for the area of a triangle with height h and base length b is the following:

A = 0.5 * b * h

This might be a relatively simple formula to remember, but let’s suppose you have to compute a more complex formula. Then suppose you have to compute this formula over and over again for many inputs. Suddenly, it becomes more of a hassle to keep copying and pasting the same formula over and over again in your code. Enter functions:

def area(b, h):
    return 0.5 * b * h

A function allows you to encapsulate Python code that you can execute over and over again. You create a function by using the keyword def followed by the function name (in this case, area) followed by parentheses, which contain a comma-delimited list of parameters (i.e. variables available for use in the Python code contained in the function).

In this case, we have two parameters: b and h. The function then outputs the triangle area as defined above. Note that in order to output our result, we must use the return keyword. If we do not use it, the function will return a special value called None.

Finally, an important detail to note is that any Python code that we are encapsulating in this function must have at least one tab preceding each line. Otherwise, Python will not recognize the code as part of the function and will not execute if you try to call it.

Here is our new function area in action:

print(area(1, 2))

To execute a function (or call it), simply write out the function name followed by parentheses, between which you pass in a comma-delimited set of values for each of the parameters of the function. This call will output:

1

Note that function names are variables, so in general, be sure not to assign variable names that are already assigned to functions!

Given that function names are also variables, as was illustrated in the previous lesson, using function names are more robust to typos compared to typing out the same Python code over and over again.

Finally, it should be noted that although this is the first time we are discussing functions, it is not the first time we have used them. print itself is a function!

Let’s now practice using functions in Python:

  • Create a function that sums two numbers together. What parameters does your function need to accept? What operation do you need to perform with those parameters? What result do you need to output at the end? (solution)

  • How would you modify your function from the previous question to sum four numbers instead of just two? (solution)

If you feel comfortable with these questions, feel free to move on to Lesson 5!