Updated functions.txt

Jack Morgan authored
revision e9402c8b79c1cc0abe53d7a68dce8e718b2a3987
# Functional Programming

When we build larger and larger programs, you will probably want to do the same thing over and over again at different points. We haven't had many of these moment arise just yet, as our programs have been quite small.

TODO: Add image of repeated code

What happens if we want to change some logic in the code? We would have to edit the code every place it occurs, which is 3 in the example above.

But the main reason for functions is functional decomposition, which sounds fancy but really means breaking the program down into sensible chunks that we can reuse. By using functions, we can have a complicated code section in one place. So if any changes are needed, we only need to change it

The solution is to write the code we want to use multiple times separate to the main program, ONCE, and telling the program to run that code
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.

Think of a function like a black-box

Functions have several 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

> 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.