fruits = ["apple", "banana", "pear", "strawberry"] for fruit in fruits: triple_fruit = fruit*3 print(triple_fruit) names = ["Claire", "Peter", "Shakil", "Malika"] for name in names: triple_name = name*3 print(triple_name)
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 print(triple_element) 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.