amortization/loan table without using pandas - python

What would be the best way to create a monthly amortization table without using pandas? Say I am given the amount of the loan, the annual interest rate, and the duration in years. How can I make a table that gives the period, beginning balance, principle, interest, and then the ending balance? And then the amount in the ending be equal to 0.
For example if I had a 150,000 loan, 10% rate, and a duration of 25 years (300 months), I don't want to use user input on this though
Formatted something like this (output will be super long I know):
month begin bal. interest principal end bal.
1 xxxx xxxx xxxx xxxx
.
.
I can attach what I have started on, but I know it is horrible lol, I am horrible with formulas/tables in Python it just does not click with me so I am struggling. Anything will help, thanks!
#p = r(pv)/(1-(1+r)**-n)
loan = 150000
rate = 10/100 #10%
term = 25 #25 years
for i in range(loanTerm):
print("month. begin bal. interest. principal. ending bal")
beginB = loanAmt
pv = loan
r = rate/100
n = term*12
p = r(pv)/(1-(1+r)**-n)
^ I know that is a very sad attempt with many errors I am embarrassed LOL just don't even know where to start. Let me know if there is anything I need to clarify!

Well, to start out with, you compute all of your constants before the loop.
#p = r(pv)/(1-(1+r)**-n)
loan = 150000
rate = 10/100 #10%
term = 25
mo_rate = rate/12
mo_term = term*12
factor = (1 + mo_rate) ** mo_term
pmt = round(loan * (mo_rate * factor) / (factor - 1), 2)
print( "Payments are", pmt, "per month")
balance = loan
print( "month\tbal\tint\tprin\tending" )
for i in range(mo_term):
interest = balance * mo_rate
ending = balance + interest - pmt
print( f"{i}\t{balance:.2f}\t{interest:.2f}\t{pmt-interest:.2f}\t{ending:.2f}" )
balance = ending

Related

Differing python codes for same desired result produce differing results...trying to understand why

I have posted this on a different site, but haven't received an answer there...so posting here to get an answer that will help me understand what is going on. My original post is below:
So, I did my own code for this before going back and viewing the video of the instructor walking through this exercise.
My code:
(01) hours = input('How many hours did you work?')
(02) rate = input('How much do you make per hour?')
(03) if float(hours) <= 40:
(04) strhrs = hours # strhrs = straight-time hours
(05) else:
(06) reghrs = 40
(07) othrs = float(hours)-40 # othrs = over-time hours
(08) strhrs = 0
(09) if strhrs != 0:
(10) pay = float(strhrs)*float(rate)
(11) else:
(12) regpay = float(reghrs)*float(rate)
(13) otpay = (float(rate)*1.5)*float(othrs)
(14) pay = regpay+otpay
(15) print(pay)
Then, I went back and watch the video covering this exercise. Obviously our codes are going to be a little different. Here is what the instructor coded:
Instructor's code:
(01) sh = input("Enter Hours: ")
(02) sr = input("Enter Rate: ")
(03) fh = float(sh)
(04) fr = float(sr)
(05)
(06) if fh > 40 :
(07) reg = fr * fh
(08) otp = (fh-40.0)*(fr*0.5)
(09) xp = reg + otp
(10) else:
(11) xp = hours * rate
(12)
(13) print("Pay:",xp)
My question is, with the "otpay" (line 13 of my code) calculating the rate1.5, I'm getting the same result as "otp" (line 8 in the instructor's code) that calculates fr0.5.
What is the difference in how Python is handling the two pieces of code (rate * 1.5 VS float rate * 0.5)?
If I put in "1.5" in the instructor's code, the result is complete different (it calculates to 2.5 times the normal rate of pay instead of 1.5 times the normal rate of pay). I'm not seeing what the difference in syntax is that would cause this to happen.
First, a comment on your code: What's the difference between straight-time hours and regular hours? There is none. You could simplify your code by not making that distinction. Also, all those float casts are unnecessary AFAICT.
Like this (untested)
hours = input('How many hours did you work?')
rate = input('How much do you make per hour?')
if hours <= 40:
reghrs = hours # reghrs = regular hours
othrs = 0 # othrs = over-time hours
else:
reghrs = 40
othrs = hours-40
regpay = reghrs*rate
otpay = (rate*1.5)*othrs
pay = regpay+otpay
print(pay)
To answer your question: You're just using a different way to come to the same result. You're computing payment for the first 40 hours (regpay) + payment for the overtime time (otpay). Your instructor is computing regular payment for the time worked (reg) + additional payment for overtime (otp).
Btw: Please tell your instructor to use better variable names.

How do I make a simple interest calculator

I'm trying to do a challenge to practice. I'm trying to use an input to decide how much you would pay on a loan. Really basic stuff - but when I print I'm getting whatever was answered in the input repeating over and over again and I can't figure out where I'm going wrong. The code I'm trying to run is:
# $200 a month at 1.7% interest a year. Automate total based on months using user input.
months_given = input("How many months? ")
monthly_base = 200
yearly_tax = (1.7 / 100 / 12)
monthly_tax = (200 * yearly_tax)
monthly_total = int(monthly_tax + 200)
total = int(months_given * monthly_total)
print(f"You will need to pay: ${round(total, 2)}")
I've tried using for/while loops but I'm not proficient with those yet and am still trying to understand how they work exactly.
You need to parse your input first then use it.
when you use input it return str.
in this total = int(months_given * monthly_total) line. months_given is str and when you use * operator and second operand is an int, str value repeated.
correct:
months_given = input("How many months? ")
months_given = int(months_given) # <-- here
monthly_base = 200
yearly_tax = (1.7 / 100 / 12)
monthly_tax = (200 * yearly_tax)
monthly_total = int(monthly_tax + 200)
total = int(months_given * monthly_total)
print(f"You will need to pay: ${round(total, 2)}")

Working with commas in output

I'm in an intro programming class and am lost. We've had several labs that required knowledge that we haven't been taught but I've managed to find out what I need on google (as nobody responds to the class message board) but this one has me pretty frustrated. I'll include a pastebin link here: https://pastebin.com/6JBD6NNA
`principal = input()
print('Enter the Principal Value of your investment: $', float(principal))
time = input()
print('\nEnter the Time(in years) you plan to save your investment: ', int(time))
rate = input()
print('\nEnter the Rate (2% = 0.02) you will collect on your investment: ', float(rate))
interest = (float(principal) * float(rate)) * int(time)
final_value = float(principal) + float(interest)
print('\nThe Final Value of your investment will be: $%.2f' % final_value)`
So I need the output of the dollar amounts to have a comma ($27,500.00) but I have no idea how to do this. I've seen a couple of solutions on this site and others but I can't get them to work. PLEASE can someone help me?
In Python 2.7 or above, you can use
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
This is documented in PEP 378.
Source: Python Add Comma Into Number String
Here is a working example:
principal = float(input('Enter the Principal Value of your investment: $'))
time = int(input('\nEnter the Time(in years) you plan to save your investment: '))
rate = float(input('\nEnter the Rate (2% = 0.02) you will collect on your investment: '))
interest = principal * rate * time
final_value = principal + interest
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
Your last line should be:
print ("\nThe Final Value of your investment will be: ${:,.2f}".format(final_value))

Loan calculator program

So far I have been coding this all week trying to get it to work.
It should come out as this:
Please enter Amount that you would like to borrow(£): 4000
Please enter Duration of the loan(Years):2
Please enter the interest rate (%):6
The total amount of interest for 2 (years) is: £480.00
The total amount of the period for 2 (years) is £4480.00
You will pay £186.67 per month for 24 months.
Do you wish to calculate a new loan payment(Y or N)
Code:
monthlypayment = 0 #Variable
loanamount = 0 #Variable
interestrate = 0 #Variable
numberofpayments = 0 #Variable
loandurationinyears = 0 #Variable
loanamount = input("Please enter the amount that you would like to borrow(£) ")
loandurationinyears = input("How many years will it take you to pay off the loan? ")
interestrate = input("What is the interest rate on the loan? ")
#Convert the strings into floating numbers
loandurationinyears = float(loandurationinyears)
loanamount = float(loanamount)
interestrate = float(interestrate)
#Since payments are once per month, number of payments is number of years for the loan
numberofpayments = loandurationinyears*12
#calculate the monthly payment based on the formula
monthlypayment = (loanamount * interestrate * (1+ interestrate)
* numberofpayments / ((1 + interestrate) * numberofpayments -1))
#Result to the program
print("Your monthly payment will be " + str(monthlypayment))
looks to me like the only thing you're missing in the code above from what you described is a while loop. This will allow your program to calculate the loan and run the program over and over again until the user inputs no, in which case the program exits. all what you have to do is:
YorNo = input("Do you wish to calculate a loan payment")
YorNo.Title()
while YorNo != "n":
#Your code goes here
YorNo = input("Do you wish to calculate a loan payment")
YorNo.Title()
print("Thank you for using the program")
In case you dont understand this, baisically, you type the first 3 lines just before your code. Then you leave an indentation and type your code after them. Once your done, you type in the 3rd and 4th line. Then, simply go back that indentation (to show the program that this isnt part of the loop.) If im not mistaken, the result of this will be:
You will be asked wether you want to calculate a loan
If you answer "y" your code will run and the loan will be calculated and printed to the user
Then you will be asked again. The above will repeat until you input "n"
the N cant be capitalised

Syntax error in Python trying to calculate complicated interest

Here I have the following attemp to calculate complicated interest and mortgage interest for example. However it gives me syntax error on the TotalMonthsMortgage = TotalMonthsMortgage - 1.0 marking the first TotalMonthsMortgage /the one on the left/ and if I quote it it marks the next line AlreadyPaidAmount = AlreadyPaidAmount+TotalAmountMortgage/TotalMonthsMortgage marking the AlreadyPaidAmount on the left. What did I do wrong as I couldn't find mistake myself?
## Complicated interest is the bank interest for example charged for mortgage loans
TotalAmountMortgage = float(raw_input('Enter the total amount of the mortgage to be taken:')) ##this is Principal
TotalYearsMortgage = float(raw_input('Enter the number of total years of the mortgage to be taken:'))
TotalMonthsMortgage = float(TotalYearsMortgage*12.0)
TotalYearsFixedInterest = float(raw_input('Enter the number of years with fixed interest mortgage to be taken:'))
TotalMonthsFixedInterest = 12.0*TotalYearsFixedInterest
FixedInterest = float(raw_input('Enter fixed interest for the mortgage to be taken:'))
FloatingInterest = float(raw_input('Enter floating interest for the mortgage to be taken:'))
PoolInterestPaid = 0.0
MonthlyPayment = 0.0
AlreadyPaidAmount = 0.0
FixedPayment = float(TotalAmountMortgage/TotalMonthsMortgage)
TotalPayment = float
while (TotalMonthsMortgage-TotalMonthsFixedInterest)>0:
MonthlyPayment = FixedPayment+(TotalAmountMortgage-((FixedPayment*TotalMonthsFixedInterest+AlreadyPaidAmount))*FloatingInterest/1200
TotalMonthsMortgage = TotalMonthsMortgage - 1.0
AlreadyPaidAmount = AlreadyPaidAmount+TotalAmountMortgage/TotalMonthsMortgage
TotalPayment = (TotalAmountMortgage*FixedInterest*TotalMonthsFixedInterest)/TotalMonthsMortgage+(TotalAmountMortgage*TotalMonthsFixedInterest)/TotalMonthsMortgage+PoolInterestPaid
print TotalPayment ##This is the total amount to be paid
print (TotalPayment - TotalAmountMortgage) ##This is the amount of intererst to be paid over time
print (TotalPayment - TotalAmountMortgage)/TotalMonthsMortgage ##This is the amount of monthly payment
You have too many parenthesis on the preceding line, you probably wanted one on the end too:
MonthlyPayment = FixedPayment + (
TotalAmountMortgage - (
(FixedPayment * TotalMonthsFixedInterest + AlreadyPaidAmount)
) * FloatingInterest / 1200)
----------------------^
I had to break the line across multiple lines to illustrate the problem, you may want to do the same to keep your code readable at least.
Because Python allows you to break the expression across multiple lines when using parenthesis, Python cannot detect when you forgot a closing parenthesis until the next line of code. The same applies to square brackets ([]), and curly braces ({}).
The rule of thumb therefor is to look at the preceding line too, when you encounter a syntax error.
You are missing a paren on this line:
MonthlyPayment = FixedPayment+(TotalAmountMortgage-((FixedPayment*TotalMonthsFixedInterest+AlreadyPaidAmount))*FloatingInterest/1200
Put a close paren at the end and you should be good to go.

Categories