Functions

Contents

Functions#

Broadly defined, a function is a block of reusable code that performs a specific task. Often, a function takes an input, transforms the input, and returns an output.

For those of you who remember high school algebra, the function f(x) = x + 1 means that given an input x, the function will return x + 1. For example, if I substituted 2 for x, my function would read f(2) = 2 + 1, or f(2) = 3. In this case, my input was 2, the transformation was to add 1, and the output was 3. These are the basic concepts that make up a function in Python as well!

In a python notebook, let’s write a Python function that prints the output from our alegebraic equation f(x) = x + 1 above.

def add_one(x):
    print(x + 1)

Let’s break that down. When creating a function, we begin by writing def before our chosen function name. After the name, we need a closed parentheses (), which in this case, takes one argument (or input), which we will temporarily call x (we can name this parameter whatever we want, as long as we use the same name within the body of the function). Then, we end the first line with a :, return, and indent by 4 spaces to write code describing what this function should “do.” In this case, we want the function to print the result of adding 1 to our input, or x. Remember, we need parentheses every time we print something!

Next, if we want to call our function, we will need to actually pass in an argument to see a result! Let’s add the following line of code below our function (make sure this next line isn’t indented).

add_one(2)
3

To see the magic of the function in action, try going back to your text editor and adding extra lines of code with different arguments, making sure to hit “save” after doing so.

add_one(155)
add_one(5)
add_one(-1)
156
6
0

Note that writing a function this way only prints the result, but does not actually return it. If we wanted our function to actually perform the operation AND print it, we could revise our code as follows.

def add_one(x):
    result = x + 1
    print(result)
    return(result)
add_one(27)
28
28

challenge:#

Write a function that greets a person by name. For example, it prints a string “Good morning, Filipa”, but changes the name based on whatever is input into the function as a parameter.