Putting It All Together:
- Example: Imagine we want to create a loan calculator that, given a loan balance, its annual percentage rate, and a monthly payment, will calculate the interest accrued and the remaining balance on the loan after one month.
python
1# Get the loan details
2loanBalance = float(input("How much money do you owe, in dollars?\n")) # $50,000
3apr = float(input("What is the annual percentage rate of the loan?\n")) # 3
4payment = float(input("How much will you pay monthly, in dollars?\n")) # $1,000
5
6# Divide apr by 100 to make a percent, and 12 to make monthly
7monthlyRate = apr / 100 / 12
8
9# Add in interest
10interestAccrued = loanBalance * monthlyRate
11loanBalance = loanBalance + interestAccrued
12
13# Make payment
14loanBalance = loanBalance - payment
15
16# Print results after this month
17print(f"Paid ${payment:,.2f}; ${interestAccrued:,.2f} was interest.", end="")
18print(f" Now I owe ${loanBalance:,.2f}")-
In lines 2-4 we can collect details of the loan from the user.
-
Line 7 calculates the monthly rate by dividing the annual percentage rate by 100, and then by 12 to convert the annual rate to a monthly rate.
-
In lines 10-11 the interest is added into the loanBalance variable.
-
Then, the results are printed. Note the end argument on line 17 changes the ending character to a space instead of a new line.
-
Output: (calculated results for only one month)
1How much money do you owe, in dollars?
250000
3What is the annual percentage rate of the loan?
43
5How much will you pay monthly, in dollars?
61000
7Paid $1,000.00; $125.00 was interest. Now I owe $49,125.00