Write a function that computes the balance of a bank account with a given initial balance and interest rate, after a given number of years. Assume interest is compounded yearly.
I am having the error " ValueError: unsupported format character 'I' (0x49) at index 28"
Here is my code so far.
def BankBalance():
InputB = 1000
return InputB
print("Your initial balance is $1000")
def Interest():
InputI = 0.05
return InputI
print("The rate of interest is 5%")
def CountNumber():
InputN = float(input("Please enter the number of times per year you would like your interest to be compounded: "))
return InputN
def Time():
InputT = float(input("Please enter the number of years you need to compund interest for:"))
return InputT
def Compount_Interest(InputB, InputI, InputT, InputN):
Cinterest = (InputB*(1+(InputI % InputN))**(InputN * InputT))
print("The compound interest for %.InputT years is %.Cinterest" %Cinterest)
B = BankBalance()
I = Interest()
N = CountNumber()
T = Time()
Compount_Interest(B, I, N, T)
Here is how you would do it.
def main():
# Getting input for Balance
balance = float(input("Balance: $ "))
# Getting input for Interest Rate
intRate = float(input("Interest Rate (%) : "))
# Getting input for Number of Years
years = int(input("Years: "))
newBalance = calcBalance(balance, intRate, years)
print ("New baance: $%.2f" %(newBalance))
def calcBalance(bal, int, yrs):
newBal = bal
for i in range(yrs):
newBal = newBal + newBal * int/100
return newBal
# Program run
main()
You are trying to use your variable as a function.
Try this instead :
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
Python, and most other programming languages, don't assume that two adjacent mathematical expressions with no operator between them means multiplication. You are missing a multiplication operator (*) between InputB and the rest of the expression:
Cinterest = (InputB * (1+(InputI % InputN))**(InputN * InputT))
# Here -------------^
Related
I´m learning Python at one of my college classes and I was asked to create a "Loan Calculator".... I might have an idea but I´m not sure how to fix an error that I´m getting TypeError: 'float' object is not subscriptable
This is the announcement
The user has to enter the cost of the loan, interest rate and the number of years of the loan.
Calculate the monthly payments with the following formula:
M = L[i(1+i)^n]/[(1+i)^(n)-1]
Data:
M = monthly payment
L = loan amount
i = interest rate (remember that 5%, i = 0.05)
n = number of payments
And this is my code:
# Loan Calculator
# Equation: M = L[i(1+i)^n]/[(1+i)(n)-1]
print("Loan Calculator")
L = float(input("Loan amount: "))
i = float(input("Interest rate: "))
# Remember: 5% ---> i=0.05
n = float(input("Number of payments: "))
M = (L[i*(1+i)**n]/[(1+i)**(n)-1])
# M = Monthly payment
print("Monthly payment: " + M)
PS: I first thought I was missing convert "M" into a string, but after I changed to
print("Monthly payment: " + str(M))
I'm still getting the same error... Please help!
Needed a few changes:
# Loan Calculator
# Equation: M = L[i(1+i)^n]/[(1+i)(n)-1]
print("Loan Calculator")
L = float(input("Loan amount: "))
i = float(input("Interest rate: "))
# Remember: 5% ---> i=0.05
n = float(input("Number of payments: "))
M = L*(i*(1+i)**n)/((1+i)**(n)-1)
# M = Monthly payment
print("Monthly payment: " , M)
Using some arbitrary values:
Loan Calculator
Loan amount: 1000
Interest rate: 9
Number of payments: 100
('Monthly payment: ', 9000.0)
For this you have to add the annual contribution to the beginning of the year (the principal total) before computing interest for that year.
I am stuck and need help. This is what I have so far:
def main():
print("Future Value Program - Version 2")
print()
principal = eval(input("Enter Initial Principal:"))
contribution = eval(input("Enter Annual Contribution:"))
apr = eval(input("Enter Annual Percentage Rate (decimal):"))
yrs = eval(input("Enter Number of Years:"))
for k in range (1, yrs):
principal= principal * (1 + apr)
print()
print( yrs,) ": Amount $", int(principal * 100 + 0.5)/100)
main()
It is supposed to look like this:
Future Value Program - Version 2
Enter Initial Principal: 1000.00
Enter Annual Contribution: 100.00
Enter Annual Percentage Rate (decimal): 0.034
Enter Number of Years: 5
Year 1: Amount $ 1137.4
Year 2: Amount $ 1279.47
Year 3: Amount $ 1426.37
Year 4: Amount $ 1578.27
Year 5: Amount $ 1735.33
The value in 5 years is $ 1735.33
Here's a working example that produces the expected output:
def main():
print("Future Value Program - Version 2")
print()
principal = float(input("Enter Initial Principal: "))
contribution = float(input("Enter Annual Contribution: "))
apr = float(input("Enter Annual Percentage Rate (decimal): "))
yrs = int(input("Enter Number of Years: "))
print()
for yr in range(1, yrs + 1):
principal += contribution
principal = int(((principal * (1 + apr)) * 100) + 0.5) / 100
print("Year {0}: Amount $ {1}".format(yr, principal))
print()
print("The value in {0} years is $ {1}".format(yrs, principal))
if __name__ == '__main__':
main()
There were a few problems with the example in the question:
A syntax error in the print statement on line 12. Calling print with parens means all the arguments should be enclosed inside the parens. Python interpreted the errant paren as the end of arguments passed to print.
As noted by others, you shouldn't call eval on the inputs. Call float for floating point numbers, int for integers.
The range operator had an off by one error.
As noted by others, print is called outside of the loop, so intermediate states of the principal aren't output.
As far as basic maths, it seems as though adding the contribution was left out.
As per the expected output, the final print was missing.
I am doing this assignment. when i input the number of months it is one printing one month. rather it be 5 months or 17 months its only printing 1 months total.
https://drive.google.com/file/d/0B_K2RFTege5uZ2M5cWFuaGVvMzA/view?usp=sharing
Here is what i have so far what am i over looking thank you
calc = input('Enter y or n to calculate your CDs worth?')
month= int(input('Select your number of months'))
while calc == 'y':
while month > 0:
amount = int(input('Please enter the amount:'))
percent= float(input('Please enter the annual percentage:'))
calc= amount + amount* percent/ 1200
print(calc)
You would want to use a for loop rather than while in this sense since you are doing a set amount of operations. You also were reusing calc and assigning calc to from a String to a float, generally a bad idea. The main problem is the formula builds upon the previously calculated number, it starts off with the initial amount entered, 10000 + 10000 * 5.75 / 1200 = 10047.91, then uses 10047.91 in the next calculation, instead of 10000, you never were reusing the previously calculated number, so you weren't getting the right answer. This should do it:
calc = input('Enter y or n to calculate your CDs worth?')
if calc == 'y':
month = int(input('Select your number of months'))
amount = int(input('Please enter the amount:'))
percent = float(input('Please enter the annual percentage:'))
for i in range(month):
if i == 0:
calcAmount = amount + ((amount * percent) / 1200)
else:
calcAmount = calcAmount + ((calcAmount * percent) / 1200)
print calcAmount
I am currently learning python through a video tutorial on youtube, and have come up against a formula I cannot seem to grasp, as nothing looks right to me. The basic concept of the excersise is to make a mortgage calculator that asks the user to input 3 pieces of information, Loan Amount, Interest Rate, and Loan Term (years)
then it calculates the monthly payments to the user. here is my code:
__author__ = 'Rick'
# This program calculates monthly repayments on an interest rate loan/mortgage.
loanAmount = input("How much do you want to borrow? \n")
interestRate = input("What is the interest rate on your loan? \n")
repaymentLength = input("How many years to repay your loan? \n")
#converting the string input variables to float
loanAmount = float(loanAmount)
interestRate = float(interestRate)
repaymentLength = float(repaymentLength)
#working out the interest rate to a decimal number
interestCalculation = interestRate / 100
print(interestRate)
print(interestCalculation)
#working out the number of payments over the course of the loan period.
numberOfPayments = repaymentLength*12
#Formula
#M = L[i(1+i)n] / [(1+i)n-1]
# * M = Monthly Payment (what were trying to find out)
# * L = Loan Amount (loanAmount)
# * I = Interest Rate (for an interest rate of 5%, i = 0.05 (interestCalculation)
# * N = Number of Payments (repaymentLength)
monthlyRepaymentCost = loanAmount * interestCalculation * (1+interestCalculation) * numberOfPayments / ((1+interestCalculation) * numberOfPayments - 1)
#THIS IS FROM ANOTHER BIT OF CODE THAT IS SUPPOSE TO BE RIGHT BUT ISNT---
# repaymentCost = loanAmount * interestRate * (1+ interestRate) * numberOfPayments / ((1 + interestRate) * numberOfPayments -1)
#working out the total cost of the repayment over the full term of the loan
totalCharge = (monthlyRepaymentCost * numberOfPayments) - loanAmount
print("You want to borrow £" + str(loanAmount) + " over " + str(repaymentLength) + " years, with an interest rate of " + str(interestRate) + "%!")
print("Your monthly repayment will be £" + str(monthlyRepaymentCost))
print("Your monthly repayment will be £%.2f " % monthlyRepaymentCost)
print("The total charge on this loan will be £%.2f !" % totalCharge)
Everything works, but the value it throws out at the end is completely wrong... a £100 loan with an interest rate of 10% over 1 year shouldn't be making me pay £0.83 per month. Any help in getting my head around this equation to help me understand would be greatly appreciated.
With the help of examples, this is what I did.
# Formula for mortgage calculator
# M = L(I(1 + I)**N) / ((1 + I)**N - 1)
# M = Monthly Payment, L = Loan, I = Interest, N = Number of payments, ** = exponent
# Declares and asks for user to input loan amount. Then converts to float
loanAmount = input('Enter loan amount \n')
loanAmount = float(loanAmount)
# Declares and asks user to input number of payments in years. Then converts to float. Years * 12 to get
# total number of months
years = input('How many years will you have the loan? \n')
years = float(years) * 12
# Declares and asks user to input interest rate. Then converts to float and input interest rate is /100/12
interestRate = input('Enter Interest Rate \n')
interestRate = float(interestRate) / 100 / 12
# Formula to calculate monthly payments
mortgagePayment = loanAmount * (interestRate * (1 + interestRate)
** years) / ((1 + interestRate) ** years - 1)
# Prints monthly payment on next line and reformat the string to a float using 2 decimal places
print("The monthly mortgage payment is\n (%.2f) " % mortgagePayment)
This mortgage package does it nicely:
>>> import mortgage
>>> m=mortgage.Mortgage(interest=0.0375, amount=350000, months=360)
>>> mortgage.print_summary(m)
Rate: 0.037500
Month Growth: 1.003125
APY: 0.038151
Payoff Years: 30
Payoff Months: 360
Amount: 350000.00
Monthly Payment: 1620.91
Annual Payment: 19450.92
Total Payout: 583527.60
I also watched this youtube video and had the same problem.
I'm a python newbie so bear with me.
The instructors in the video were using python3 and I am using python2
so I am not sure if all the syntax are the same. But using some information found in this thread and info from this link: (http://www.wikihow.com/Calculate-Mortgage-Payments) I was able to get the answer. (My calculations matched an online mortgage calculator)
#!/usr/bin/env python
# The formula I used:
M = L * ((I * ((1+I) ** n)) / ((1+I) ** n - 1))
# My code (probably not very eloquent but it worked)
# monthly payment
M = None
# loan_amount
L = None
# interest rate
I = None
# number of payments
n = None
L = raw_input("Enter loan amount: ")
L = float(L)
print(L)
I = raw_input("Enter interest rate: ")
I = float(I)/100/12
print(I)
n = raw_input("Enter number of payments: ")
n = float(n)
print(n)
M = L * ((I * ((1+I) ** n)) / ((1+I) ** n - 1))
M = str(M)
print("\n")
print("Monthly payment is " + M)
Apparently you copied the formula wrong.
wrong: * numberOfPayments
correct: ** numberOfPayments
note: it appears twice in the formula
note: in python, ** is "to the power of" operator.
This worked pretty well for me. Not exact, as loan calculators usually go by days, and I'm lazy so I go by months but here's a simple one I wrote that is accurate enough to be practical.
L = input("How much will you be borrowing? ")
L = float(L)
print(L)
N = input("How many years will you be paying this loan off? ")
N = float(N) *12
print(N)
I = input("What is the interest in percents that you will be paying? Ex, 10% = 10, 5% = 5, etc. ")
I = float(I)/100
print(I)
M = (L/N) + I*(L/N)
float(M)
print("Your monthly payment will be: ")
print(M)
I also came accross this problem and this is my solution
loan = input('Enter Loan Amount: ')
loan = float(loan)
numberOfPayments = input('Enter Loan payments in years: ')
numberOfPayments = float(numberOfPayments) * 12
interest = input('Annuel interest Rate: ')
interest = float(interest)/100/12
monthlyPayments = loan * (interest * (1 + interest) ** numberOfPayments) / ((1 + interest) ** numberOfPayments - 1)
print (round(monthlyPayments))
I'm trying to write a function that calculates the cost of a loan, but I keep getting the cost of the loan to be the negative value of what the user inputs as the amount of the loan.
#define monthly payment
def MonthlyPayment (ammountOfLoan, numberOfPeriods,yearlyInterestRate):
ammountOfLoan = 0
numberOfPeriods = 0
yearlyInterestRate = 0
payment = [(yearlyInterestRate/12)/(1-(1+yearlyInterestRate/12))**(-numberOfPeriods)] * ammountOfLoan
return (payment)
#define cost of loan
def LoanCost(principal, month, payment):
period = 0
month = 0
payment = 0
cost = period * payment - principal
return (cost)
#calculate cost of loan
def main():
loan = float(raw_input("What is the ammount of your loan? "))
period = float(raw_input("How many months will you make payments? "))
rate = float(raw_input("What is the interest rate? "))
rate = rate / 100
MonthlyPayment(loan, period, rate)
costOfLoan = LoanCost(loan, period, rate)
print "The cost of the loan is $" + str(costOfLoan)
#run main
main()
LoanCost is setting period and payment to 0 (you're making the same mistake in MonthlyPayment, as well), then multiplying them. So you're ending up with (0 * 0) - principal. You're also calling the second parameter "month", when what you really mean is "period".
Just to clarify, when you have a function definition like
def func(a, b, c):
You shouldn't initialize a, b, and c to zero inside the function body. You're overwriting their values when you do that. Just use them directly.