Before we get into functions, one of the main building blocks of programming, it is important to understand the idea of abstraction. Abstraction is managing complexity by removing details and pushing them down to a lower level.
Consider a car for example. Many people know how to drive a car, but not everyone necessarily knows how all the different minute parts of the car work together, like those shown in the picture above. Cars are built with a ton of complexity, but that complexity is managed by much fewer components that make it easier for a human to operate. In order to drive a car, we only need to know how to operate things like the steering wheel, gas, brakes, turn signals, and a few other features. Rather than needing a full understanding of all the parts under the hood, we just need an understanding of a few things from the driver seat.
Just like how the complexity of a car can be managed by a few simpler features, we can manage complex components of a program by using simpler commands and structures within Python. We’ve already seen several ways that we can manage complexity through abstraction within Python, such as:
Beyond these, the primary way that we can also create abstraction within a program is by creating user-defined functions. This allows us to structure more repetitive or complex blocks of code in way that makes it easier to execute and read as a the programmer. Here is an example:
# Name: loan_value
# Purpose: Calculate the value of a loan based on given inputs
# Inputs: principal balance, interest rate, time in years
# Returns: total value of the loan
def loan_value(principal, rate, time):
growth_factor = (1 + rate) ** time
total_value = principal * growth_factor
return total_value
# compare various loans:
print(loan_value(5000, 0.05, 7)) # $5000 loan at 5% over 7 years
print(loan_value(5000, 0.03, 10)) # $5000 loan at 3% over 10 years
print(loan_value(7000, 0.065, 5)) # $6000 loan at 6.5% over 5 years
We’ll get more into the concrete syntax of the code above shortly, but what we should notice is that the function loan_value allows us to easily calculate the value of a loan, without rewriting the steps in order to calculate it each time. Rather than copying and pasting the calculations on lines 6-8 every time we want to calculate the value of a new loan, we can declare these steps in a function, and then simply call the function using one line of code like we do on lines 11-13.
This is just one example of how we can take the complexity of certain tasks out of programming flow using abstraction.