Hello everyone, welcome back to the “Hands-On” series!
In the last episode, we successfully used Python to calculate <span>123 + 456</span>. You might think, “Is that it? My calculator is much faster than yours.”
Hold on, that was just a warm-up. Today, we are going to tackle something more “advanced”—a problem that even calculators find troublesome, and a bit “scary”—Compound Interest.
What is Compound Interest? A Story of “Interest on Interest”
To help you understand instantly, let’s take an example. Suppose you borrowed 10,000 yuan from an online lending platform, with a monthly interest rate of 2% (this is just an example; please adhere to national regulations for actual rates).
-
Simple Interest: Very simple, the interest is fixed every month, calculated on the principal of 10,000 yuan, which is 200 yuan.
-
Compound Interest: This is where it gets “scary”.
-
In the first month, the interest is
<span>10000 * 2% = 200 yuan</span>. At this point, you owe a total of<span>10200 yuan</span>. -
In the second month, the principal for calculating interest is no longer 10,000, but has changed to
<span>10200</span>! The interest is<span>10200 * 2% = 204 yuan</span>. You owe a total of<span>10404 yuan</span>. -
… and so on, your principal increases every month, and the interest grows like a snowball.
This is “interest on interest”. Its calculation formula is: Final Amount = Principal × (1 + Interest Rate) ^ Number of Periods
Now, let’s have Python help us act as a “financial advisor” and calculate this amount.
Calculating Compound Interest with Python
Please open the <span>My_Python_Project</span> folder we created in the last episode and open it with VS Code. We will continue writing code in the <span>main.py</span> file.
# --- Let's calculate compound interest ---
# Set initial parameters
principal = 10000 # Principal (本金)
monthly_rate = 0.02 # Monthly interest rate (月利率)
periods = 12 # Number of periods, here it is 12 months (期数)
# Calculate final amount based on the formula
# Note: In Python, the exponentiation (^) symbol is represented by two asterisks **
final_amount = principal * (1 + monthly_rate) ** periods
# Print the result
# We add some text to make the output clearer
print("After 12 months of compound interest calculation, the final total amount is:")
print(final_amount)
Now, run <span>python main.py</span> in the terminal below, and you will get the result: <span>12682</span> (followed by a long string of decimals). Did you see that? In one year, the principal of 10,000 yuan has turned into 12,682 yuan.
Knowledge Tip: In Python, addition, subtraction, multiplication, and division are represented by
<span>+</span>,<span>-</span>,<span>*</span>, and<span>/</span>. The Nth power of a number is represented by<span>**</span>. For example,<span>3 ** 2</span>is 3 raised to the power of 2, which equals 9.
Code Upgrade: Encapsulate Your Calculation Logic with a Function
The code above works, but there’s a problem: what if I want to calculate another loan (for example, a principal of 20,000, an interest rate of 1.5%, and 24 periods)? What should I do? Copy and paste the code and modify the numbers inside?
Of course, you can, but that seems very “clumsy”, and if you need to modify the calculation logic, you have to change it everywhere you copied and pasted, which is prone to errors.
In programming, we have a more elegant solution called Functions.
You can think of a “function” as a toolbox with inputs and outputs. You put in the raw materials (parameters), it processes them according to the preset steps (code logic), and then gives you the finished product (return value).
Let’s encapsulate the compound interest calculation into a function:
# --- Let's calculate compound interest (function upgrade version) ---
# Define a function named "calculate_compound_interest"
# It requires three input parameters: principal, rate, periods
def calculate_compound_interest(principal, rate, periods): # This is the internal logic of the function, identical to the code we wrote earlier
final_amount = principal * (1 + rate) ** periods # The "return" keyword indicates that the calculation result is output as the function's "finished product"
return final_amount
# --- Using our defined function ---
# Calculate the first loan
loan1_result = calculate_compound_interest(10000, 0.02, 12)
print("The final total amount for the first loan is:")
print(loan1_result)
# Calculate the second loan, directly calling the function with different parameters
loan2_result = calculate_compound_interest(20000, 0.015, 24)
print("The final total amount for the second loan is:")
print(loan2_result)
Run the code again, and you will see the results for both loans printed clearly. Isn’t it much cleaner and more efficient than copying and pasting code?
Note: In the world of Python, there are many pre-written functions developed by community developers (we call them “libraries” or “packages”) that can handle various complex problems. But today, we first learn to create our own tools, which is crucial for understanding programming concepts.
Why Functions Are More Powerful Than Excel Formulas?
You might say, “I can also calculate this function using a formula in Excel!”
That’s true, but functions have several huge advantages that Excel struggles to match:
-
Readability:
-
Excel Formula:
<span>=A2*(1+$B$1)^C2</span>. What do<span>A2</span>,<span>$B$1</span>, and<span>C2</span>represent? You need to drag back and forth in the table and click on cells to understand, which is very tedious. -
Python Function:
<span>calculate_compound_interest(principal=10000, rate=0.02, periods=12)</span>. The code serves as documentation, and the meaning of each parameter is clear at a glance, easily understood by anyone.
Reusability:
Excel Formula: You need to carefully drag, copy, and always pay attention to absolute references (<span>$B$1</span>) and relative references (<span>C2</span>); a small mistake can lead to errors.
Python Function: Defined once, called anywhere. The logic is encapsulated within the function, so it won’t go wrong; you just need to ensure the parameters passed are correct.
Scalability:
Imagine if your task is to calculate the compound interest for 1,000 loan records from a table. In Excel, you would need to drag down the formula for 1,000 rows. In Python, we will learn in the future that you only need to write a loop to continuously call our function, and a few lines of code can accomplish it.
Next Episode Preview
Congratulations! Today you have upgraded from a “command executor” to a “tool creator”, learning to encapsulate and reuse your code with functions.
Now, we can call the function twice to calculate two loans. But what if your boss gives you a list with 10 or even 100 loans to calculate? Should we manually call the function 100 times? That would be going back to the “manual labor” route!
Of course not!
In the next episode, we will learn how to “package” this data into a List, and then use a magical “spell”—Loop—to command Python to automatically and tirelessly process each item in the list.
When functions, lists, and loops come together, you unlock the first truly powerful capability in programming: Batch Processing. Stay tuned!