Introuction to Functions

We commonly call the following commands functions: print(), sum(), len(), min(), max(). Generally, a function displays the following pattern:

  1. It takes in an input

  2. It processes that input

  3. It returns output

For instance, we can observe this pattern if we use the len() function to find the length of a list. Below, the len() function does the following:

  1. Takes list_1 as an input

  2. Counts the length of (list_1)

  3. Returns the output 5 — the length of list_1

list_1 = [21, 0, 72, 2, 5]

print(len(list_1))

Output
5

Creating Our Own Functions

Let's say we want to create a function named square() that takes in a number as input and returns its square as output. To find the square of a number, we need to multiply that number by itself. For instance, to find the square of 66, we need to multiply 66 by itself: 6×66×6, which equals 3636 — so the square of 66 is 3636.

This is how we can create the square() function:

def square(a_number):
    squared_number = a_number * a_number
    return squared_number

To create the square() function above, we did the following:

  • Started with the def statement, where we did the following:

    • Specified the name of the function (square)

    • Specified the name of the variable (a_number) that will serve as input

    • Surrounded the input variable a_number with parentheses

    • Ended the line of code with a colon (:)

  • Specified what we want to do with the input a_number (in the code below the def statement)

    • We multiplied a_number by itself: a_number * a_number

    • Assigned the result of a_number * a_number to a variable named squared_number

  • Ended with the return statement, where we specified what we want returned as the output.

    • The output is the variable squared_number, which stores the result of a_number * a_number.

After we define the square() function, we can use it to compute the square of a number. Below, we use the function three times to compute the square of the numbers 66, 44, and 99:

  • To compute the square of 66, we use the code square(a_number=6).

  • To compute the square of 44, we use the code square(a_number=4).

  • To compute the square of 99, we use the code square(a_number=9)

a_number is the input variable and we can see that it can take various values. This enables us to use the square() function for any number we want.

Now let's practice creating functions.

Last updated