As we increase our programming skills we will be tackling big and complicated problems. These are great fun to solve but can quickly get messy if we don't have a sensible way to manage our code. When sorting out a problem, you generally break it down into smaller and smaller chunks. The same idea can be applied to the programming, by breaking it into what we call functions. Functions help us see our program as a bunch of smaller steps, and also allow us to reuse pieces of code thorough the program instead of rewriting it (we haven't had to rewrite much code yet, as our programs have been quite small).
What would happens if we want to change some complex logic in the code that was repeated several times throughout the program? We would have to edit the code every place it occurs! However if the logic was written once in a function, then we would only need to change the function to update all the times it was used.
A function can be run within your program (we call this 'calling the function' or a 'function call'), and the program will run the function before continuing where is was called.
TODO: Add diagram about calling and resuming from call.
We know what will happen in our function, but to our programs a function is a black-box system where the function takes input and can produce output, however the internal workings are unknown. This may sound odd but if you know what a function requires and what it will give you as output, the inner workings are irrelevant.
Let's look at functions in more details, they have several major properties:
- Name: a name (using variable name rules) that describes the purpose of the function. Usually contains a verb, for example, calculate_average, print_summary, or find_patient.
- Inputs: The data the function takes in for it to do it's work, and each input is called a parameter.
- Calculations: The work the function is made for (for example, the find_patient function might search through a list of patients for a given name).
- Output: Usually most functions return one piece of data to the place they were triggered, but functions can return several pieces of data or nothing at all.
#Say hello function def sayHello(): print("Hi there") #Main routine print("Hi") sayHello() print("Bye")
More explicitly consider the following conversation metaphor: A primary function may ASK a secondary function a QUESTION by calling it. The secondary function RESPONDS by returning an answer.