Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

COMPLETELY LOST

I came across with this question and I have been trying to code it but it's so hard since I just started python.

Monthly mortgage payments can be calculated using the formula:

A = (p * i) / (1- (1 + i) **(-n))

Where A is the monthly payment, P is the total amount borrowed (the principal), n is the number of months for repayment and i is the monthly interest rate. You can calculate the monthly interest rate by dividing the annual interest rate ("APR") by 12.

For example, to borrow $30,000 (P) for a 10 year term (n = 120) with an APR interest rate of 6% (i = 0.06 / 12 = 0.005), A calculates to be $333.06 - the monthly payment. The total interest paid over 10 years (always depressing!) = 120 * $333.06 - $30,000 = $9,967.38.

Assume that interest rates are fixed and the APR must lie between 1 and 10% inclusive. The term is always in years and must lie between 1 and 30 years inclusive. Payments are always monthly and the principal must lie between $1,000 and $500,000, inclusive.

Write a program that prompts the user for the three required values and then calculates and displays the monthly payment and the total interest paid over the entire term.

I seriously tried my best but I know I am still so far away from being close LOL. Any help would be greatly appreciated! Here is what I wrote so far: :(

A Mortgage Calculator

def calc_mortgage(P, i, n, APR):

   P = int(input("Enter the total amount borrowed: "))
    i = float(input("Enter monthly interest rate: "))
    n = int(input("Enter the number of months for repayment: "))
    APR = float(input("Enter annual interest rate: "))
    A = float("the value of monthly payment")

# monthly interest rate from annual interest rate divide by 12 to get monthly rate
i = APR / 12
# number of months for repayment
n = years * 12
# calculate monthly payment
A = (p * i) / (1- (1 + i) ** (-n))

if 1,000 <= p <= 500,000 and 1% <= APR <= 10% and 1 * 12 <= n <= 30 * 12

print("the value of monthly payment")

print("the value of monthly payment")

Thank you so much!!!!!!

Hi Viola,

quickly had a look at it. What I noticed so far:

1) instead of writing the numbers like 1,000, better write 1000. The comma is not valid in this case.

2) in a comparison like a <= b < c there usually is only one equality case (e.g. a <= b < c instead of a <= b <= c)

3) 1% and 10% are not recognized as numbers because of the %, instead you could write 0.01 and 0.1.

4) at the end of an if statement, there always needs to be a colon

if condition:
    do whatever

5) at the end of the function, add a return statement, so that you can output the result

1 Answer

Hi again,

I think this is what you are looking for (please double-check if it is correct). P was not defined in your code above bcause you used a lowercase and an uppercase p (they are not the same variables). I don't think that the if conditions are necessary here, but you can add them of course (you can add them all on one line, you don't need to write them over 3 lines). Also, I didn't pack the calculation into a function, it's not necessary in this case.

# enter the three required input values: P, n_years and APR
P = int(input("Enter the total amount borrowed: "))
n_years = int(input("Enter the number of years for repayment: "))
APR = float(input("Enter annual interest rate: "))

# number of months for repayment
n = n_years * 12

# monthly interest rate from annual interest rate divided by 12 to get monthly rate
i = APR / 12

# calculate monthly payment
A = (P * i) / (1- (1 + i) ** (-n))

print("Monthly payment is {}".format(A))

# calculate total interest paid
tot = A * n - P

print("Total interest paid is {}".format(tot))

There are new parts to this problem: In addition to these three inputs, the program must also take into account anniversary payments. In the "real world" of mortgages, payees can opt to make a once a year single lump sum payment directly against the principal. The rules vary from lender to lender, but for the sake of this assignment let us say that this anniversary payment must be the lesser of $5,000 or 5% of the principal remaining. The lender does not want you to pay the mortgage off too quickly! And, you must complete a full year of payments before you can make an anniversary payment. Rather than prompting every year for the amount of the payment, assume that the payment made will be the maximum possible every year. But, you must first give the user the choice of using anniversary payments or not. If the user says "yes", then apply an anniversary payment each year.

After obtaining these four inputs, you will calculate and display each monthly payment and the principal remaining after the payment. Display anniversary payments, if they are made. You must track the total amount of interest paid, the total of anniversary payments, and the total of all monthly payments. Report the number of months that the mortgage payments have been shortened as a result of making anniversary payments. Report the total cost of the mortgage, which is the sum of all anniversary payments and the total of all mortgage payments.

---------------I am stuck on the part about anniversary payment and how to loop it so that it always chooses the maximum amount that is no greater than 5000 or 0.05 * principal. I was just wondering if you could give me some hints on how to proceed. Also, when I run the code right now, it goes to the negative amount. I am not sure which step is wrong :( Here is my code:

def main():

# Obtain input parameters from the user and check for legality of each
paymentTerm = int(input("Enter payment term in years: "))
while paymentTerm < 1 or paymentTerm > 30 :
    paymentTerm = int(input("Payment term is not legal, please try again: "))
annualInterestPercent = float(input("Enter annual interest rate as %: "))
while annualInterestPercent < 1 or annualInterestPercent > 10 :
    annualInterestPercent = float(input("Annual interest rate is not legal, please try again: "))
principal = float(input("Enter principal amount in $: "))
while principal < 1000 or principal > 500000 :
    principal = float(input("Principal amount is not legal, please try again: "))
anniversaryPayment = input("Please enter (y) to apply anniversary payment and (n) otherwise: ")

# Calculate the monthly payment
termInMonths = 12 * paymentTerm
monthlyInterestRate = annualInterestPercent / 1200
monthlyPayment = principal * monthlyInterestRate / (1 - (1 + monthlyInterestRate) ** -termInMonths)
print(f"Monthly payment is ${monthlyPayment:.2f}")
while paymentTerm <= 30 :
    paymentTerm = paymentTerm + 1
    principal = principal - monthlyPayment * 12
    print(principal)
# Calculate the total interest
totalInterest = termInMonths * monthlyPayment - principal

# Display the results
print(f"Monthly payment is ${monthlyPayment:.2f}")
print(f"Total interest paid is ${totalInterest:.2f}")

main()

Well, some hint then:

I think for the anniversary payment you could make use of the minimum function.

min(5000, 0.05*principal)

The lower of the two values is chosen this way. You may have to include this in the while loop (because you need the remaining principal).

The start principle value must be copied here, so that we can use it to calculate totalInterest, otherwise the value at the end of the while loop would be used. Also, I was wondering why you increase paymentTerm in the while loop (up to 30). I'm not sure if I understood it correctly, but I think it would make more sense to decrease it and let the loop run until paymentTerm is 0, like this (I also put print(principal) at the start of the loop, so it also displays the starting principal):

    # Calculate the monthly payment
    start_principal = principal
    termInMonths = 12 * paymentTerm
    monthlyInterestRate = annualInterestPercent / 1200
    monthlyPayment = principal * monthlyInterestRate / (1 - (1 + monthlyInterestRate) ** -termInMonths)
    print("Principal remaining:")
    while paymentTerm >= 0:
        print(f"{principal:.2f}")
        paymentTerm = paymentTerm - 1
        principal = principal - monthlyPayment * 12
        # Calculate the total interest
        totalInterest = termInMonths * monthlyPayment - start_principal

The negative principal value at the end of the loop is equal to the positive total interest paid.