def calculate_monthly_payment(principal: float, term_length: float, annual_interest_rate: float) -> float:
"""
Calculate the monthly payment for a loan given the principal, term length, and annual interest rate.
The formula used to calculate the monthly payment is the annuity formula:
M = P[r(1+r)^n]/[(1+r)^n-1]
where:
P = principal
r = monthly interest rate
n = number of payments (term length * 12)
Parameters
----------
loan_amount : float
The amount of money borrowed
term_length : float
The length of the loan in years
annual_interest_rate : float
The annual interest rate of the loan
Returns
-------
float
The monthly payment for the loan
"""
monthly_interest_rate = annual_interest_rate / 12
number_of_payments = term_length * 12
monthly_payment = principal * (monthly_interest_rate * (1 + monthly_interest_rate) ** number_of_payments) / ((1 + monthly_interest_rate) ** number_of_payments - 1)
return monthly_payment
def main() -> int:
try:
principal = input("Enter the loan amount: ")
term_length = input("Enter the term length in years: ")
annual_interest_rate = input("Enter the annual interest rate (as a percentage): ")
principal = float(principal)
term_length = float(term_length)
annual_interest_rate = float(annual_interest_rate) / 100
if principal <= 0:
raise ValueError("The principal must be greater than 0 lol")
if term_length <= 0 or term_length > 100:
raise ValueError("The term length should probably be greater than 0 and no more than 100 years, you crazy?")
if annual_interest_rate <= 0:
raise ValueError("Good luck to whoever is giving you a loan with this rate lol")
if annual_interest_rate >= 1:
raise ValueError("That's a robbery! Who's charging you >= 100% interest?")
monthly_payment = calculate_monthly_payment(principal, term_length, annual_interest_rate)
print(f"The monthly payment for a loan of ${principal} over {term_length} years at an annual interest rate of {annual_interest_rate * 100}% is ${monthly_payment:.2f}")
except ValueError as e:
print(f"Invalid input: {e}")
return 1
return 0
if __name__ == "__main__":
main()