Functions are separate pieces of code (sub-programs) that you first define and then call in the program. We also name them procedures. Functions allow for extremely convenient code manipulation: you can call a function – once defined in your program – many times, depending on your needs. You don't have to write repetitive tasks from scratch over and over again. You save time and effort.
Here is an example of a simple function that prints a greeting:
def hellou():
print('Hello!')
As you can see, we define a function using the word def and the name of the function (which can be whatever you wish), followed by a pair of parentheses and a colon. This is called header line. Following this command line, constituting the function body, should be indented four spaces from the header line.
The function is called (i.e. its executed) by writing its name — along with parentheses:
hellou()
Exercise: Put the above definition and function call in a Python file — then run it. What effect did you get?
Admittedly, Python's function syntax is simple and intuitive. It doesn't take much effort to remember it.
Functions with a parameter
Functions very often have a parameter. It may be perceived as a kind of "window" in the function into which we can substitute a value that the function will then use. In other words, a parameter is a variable that allows a function to communicate with its environment. For example, if we provide our hellou() function with a parameter "name", we can then call this function on any given name:
def hellou(name):
print('Hello '+name+'!')
hellou('Rick')
Output: Hello Rick!
A function may have any number of parameters.
Exercise
Let's write a function that "catches" the largest item from the list and prints its value on the screen. We'll call our function find_highest
def find_highest(list_of_el):
highest = list_of_el[0]
for n in list_of_el[1:]:
if n > highest:
highest = n
print(highest)
The function has a parameter named list_of_el. So it searches any given list of elements (which, when invoked, we substitute for list_of_el). This is done with the for loop.
The searched highest value (highest) — we will initially compare to the first element of the list: list_of_el [0]. Then, using the for loop, we will check the following words of the list: for n in list_of_el [1:]
If the next element taken turns out to be higher than the previous one, it will be substituted to highest
if n > highest:
highest = n
In this way, we find the greatest element in the list. Let's check:
L=[0, ‑3, ‑7, ‑1, ‑9, 5]
find_highest(L)
Output: 5
What have we done in the code lines above? We've given a concrete L‑list and made our call to find_highest on it. The specific (real) list L has been inserted in place of the list_of_el parameter
L → list_of_el
And here it is, everything worked out as it should be. In addition, while learning the function, we reminded a few of the coding rules discussed earlier (the for loop, the conditional statement, and the list slicing).