Introuction to Functions
We commonly call the following commands functions: print(), sum(), len(), min(), max(). Generally, a function displays the following pattern:
It takes in an input
It processes that input
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:
Takes
list_1as an inputCounts the length of (
list_1)Returns the output
5— the length oflist_1
list_1 = [21, 0, 72, 2, 5]
print(len(list_1))
Output
5Creating 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_numberTo create the square() function above, we did the following:
Started with the
defstatement, where we did the following:Specified the name of the function (
square)Specified the name of the variable (
a_number) that will serve as inputSurrounded the input variable
a_numberwith parenthesesEnded the line of code with a colon (
:)
Specified what we want to do with the input
a_number(in the code below thedefstatement)We multiplied
a_numberby itself:a_number * a_numberAssigned the result of
a_number * a_numberto a variable namedsquared_number
Ended with the
returnstatement, where we specified what we want returned as the output.The output is the variable
squared_number, which stores the result ofa_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