Using Functions to Avoid Code Repetition
Functions are a programming concept that allows us to organize our code into sections. This organization makes code easier to read, but also allows the programmer to reuse code throughout a program. As an example, suppose you are making a program that completes the following task.
1. The user is prompted to input numbers until they input “quit”. Each input is run through the formula (input * 2 + 2), and appended to a list
2. Once the user types quit, they are prompted for a final input as a value to search for. This value is also run through the formula (input * 2 + 2), and the list is searched for the value
3. If the value is in the list, output that the value is found. Otherwise, output that the value isn’t found
For this example, the following code would implement the logic required.
Now, suppose that suddenly the logic changed, and we no longer wanted to take input * 2 + 2, but rather wanted to do input * 3 + 2. Notice that in the current code, you would need to change the logic in two places.
This is a great example of a situation where functions and code reuse become useful…