Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 3: Custom functions
Defining functions
You can create your own functions (hopefully that is not a surprise!)
As an example, let’s say you do not like Python’s abs()
function. Instead, you want to write your own function called absolute_value()
to compute the absolute value of a number.
Here is how you would define your amazing absolute_value()
function:
1 2 3 4 5 6 7 |
|
Hopefully this is self explanatory.
The code above is an example of a function definition.
The function definition is like a recipe for a dish. Your dish only gets prepared according to the recipe (i.e. the code gets executed) when you call the function, providing it with some ingredients (input). For example, you might ask Josiah-the-chef to prepare your lasagna by providing home-made pasta sheets, vegetarian ragu, Parmigiano-Reggiano PDO cheese, white sauce from a jar, etc.; and it will be done according to Josiah-the-chef’s recipe.
Image credits:
Lasagna sheets: MMFE, Lasagne Blätter01, CC BY-SA 3.0
Lasagna: via GIPHY