Python – Functions

Links to Python editor // Variables & Lists // Collections // Conditions // Loops // Working with text files // Working with libraries // Exercises

fruits = ["apple", "banana", "pear", "strawberry"]
for fruit in fruits:
    triple_fruit = fruit*3

names = ["Claire", "Peter", "Shakil", "Malika"]
for name in names:
    triple_name = name*3

The above code asks for a lot of retyping. That is why we create a function.

A function is a block of code which only runs when it is called.

You can declare a function when you reuse the same blocks of code in one script.

You can pass data, known as parameters, into a function.

A function can return data as a result.

In Python a function is defined using def name_function().

Functions are declared on top of script. You make a list of functions, you call your function later in your script.

def triple_element(list):
    for element in list:
        triple_element = element*3

triple_name = triple_element(names)
triple_fruit = triple_element(fruits)

Note: always write your code plainly, check if it works and only then, rewrite it as a function.

Exercise: solve the exercises on this page by using functions.