I am a beginner programmer and have a question regarding the calculation of future investment values based on the following formula :
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate)numberOfMonths
... ofc the numberOfMonths value is an exponent.
I have created this so far but seem to receive incorrect answers when running the program
#Question 2
investmentAmount = float(input("Enter investment amount: "))
annualInterestRate = float(input("Enter annual interest rate: "))
monthlyInterestRate = ((annualInterestRate)/10)/12
numberOfYears = eval(input("Enter number of years: "))
numberOfMonths = numberOfYears * 12
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) **\
numberOfMonths
print("Accumulated value is", futureInvestmentValue)
what do I need to fix in order to get this thing to work, any help would be appreciated thank you
annualInterestRate should be divided by 12 to get monthlyInterestRate.
The correct final formula should be
futureInvestmentValue = investmentAmount * (1 + (monthlyInterestRate/100) ** \
numberOfMonths
You can do it like this:
from __future__ import division # assuming python 2.7.xxxxx
investmentAmount = float(input("Enter investment amount: "))
annualInterestRate = float(input("Enter annual interest rate: "))
monthlyInterestRate = ((annualInterestRate)/10)/12
try:
numberOfYears = int(input("Enter number of years: "))
except Exception, R:
print "Year must be a number"
numberOfMonths = numberOfYears * 12
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) **\
numberOfMonths
print("Accumulated value is", futureInvestmentValue)
The errors are in:
monthlyInterestRate = ((annualInterestRate)/10)/12
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) **\
numberOfMonths
There are two errors i think. The first is that the interest rate is being divided by 10 when it should be divided by 100. Right now, if you enter 2, its treated as 20% interest because 2/10 = .2.
The second error is that monthlyInterestRate assumes a flat interest rate whereas futureInvestmentValue assumes a compound interest rate. It should be
monthlyInterestRate = (1 + (annualInterestRate/100))**(.1/1.2).
For example(Using /12):
print 0.05/12
print (1+0.05/12)**12
Output:
0.00416666666667
1.05116189788
The monthly interest rate compounded is not equal to the annual interest rate for a single year. Its because in one case you divide by 12, the next case you raise to the raise to the power of 12 which are not equivalent.
Example (Using **1/12)
from __future__ import division
print (1.05**(1/12))**12 #returns 1.05
investmentAmount = eval(input("Enter investment amount: "))
annualInterestRate = eval(input("Enter annual interest rate: "))
monthlyInterestRate = (annualInterestRate) / 10 / 12
numberOfYears = eval(input("Enter number of years: "))
numberOfMonths = numberOfYears * 12
futureInvestmentValue = investmentAmount * (1 + monthlyInterestRate) **\
numberOfMonths
print("Accumulated value is", futureInvestmentValue)
You just have one mistake which is "eval"
Related
*****UPDATE: Thanks to everyone who contributed. The code is alright. I figured there was a problem with the website I was using as IDLE.
I have to write a program in Python that calculates then prints specific information about a loan. The program (code below) consists of 2 functions and I have written them correctly. The only problem I have is that I have to write the second function within the first one. When I run the code, I get this error: NameError: name 'vaam' is not defined
I've just started coding last week, I hope you guys help me out with this.
Here's my program:
# Your function for calculating payment goes here
def loan(principal,annual_interest_rate,duration):
r=(annual_interest_rate)/1200
n=duration*12
if annual_interest_rate==0:
monthly_payment=principal/n
else:
monthly_payment=(principal*(r*(1+r)**n))/((1+r)**n-1)
return monthly_payment
# Your function for calculating remaining balance goes here
def vaam(principal, annual_interest_rate, duration , number_of_payments):
n=duration*12
r=(annual_interest_rate)/1200
if annual_interest_rate==0:
remaining_loan_balance=principal-principal*(number_of_payments/n)
else:
remaining_loan_balance=(principal*((1+r)**n-(1+r)**number_of_payments))/((1+r)**n-1)
return remaining_loan_balance
# Your main program goes here
principal=float(input("Enter loan amount: "))
annual_interest_rate=float(input("Enter annual interest rate (percent): "))
duration=int(input("Enter loan duration in years: "))
print('LOAN AMOUNT:',int(principal),'INTEREST RATE (PERCENT):',int(annual_interest_rate))
print('DURATION (YEARS):',int(duration),'MONTHLY PAYMENT:',int(loan(principal,annual_interest_rate,duration)))
for i in range(1,duration+1):
print('YEAR:',i,'BALANCE:',int(vaam(principal, annual_interest_rate, duration , i*12)),'TOTAL PAYMENT:',int(loan(principal,annual_interest_rate,duration)*12*i))
Try this:
# Your function for calculating payment goes here
def loan(principal, annual_interest_rate, duration):
r = (annual_interest_rate) / 1200
n = duration * 12
if annual_interest_rate == 0:
monthly_payment = principal / n
else:
monthly_payment = (principal * (r * (1 + r) ** n)) / ((1 + r) ** n - 1)
return monthly_payment
# Your function for calculating remaining balance goes here
def vaam(principal, annual_interest_rate, duration, number_of_payments):
n = duration * 12
r = (annual_interest_rate) / 1200
if annual_interest_rate == 0:
remaining_loan_balance = principal - principal * (number_of_payments / n)
else:
remaining_loan_balance = (principal * ((1 + r) ** n - (1 + r) ** number_of_payments)) / ((1 + r) ** n - 1)
return remaining_loan_balance
# Your main program goes here
principal = float(input("Enter loan amount: "))
annual_interest_rate = float(input("Enter annual interest rate (percent): "))
duration = int(input("Enter loan duration in years: "))
print('LOAN AMOUNT:', int(principal), 'INTEREST RATE (PERCENT):', int(annual_interest_rate))
print('DURATION (YEARS):', int(duration), 'MONTHLY PAYMENT:', int(loan(principal, annual_interest_rate, duration)))
for i in range(1, duration + 1):
print('YEAR:', i, 'BALANCE:', int(vaam(principal, annual_interest_rate, duration, i * 12)), 'TOTAL PAYMENT:',
int(loan(principal, annual_interest_rate, duration) * 12 * i))
Output
Enter loan amount: 5000
Enter annual interest rate (percent): 8
Enter loan duration in years: 5
LOAN AMOUNT: 5000 INTEREST RATE (PERCENT): 8
DURATION (YEARS): 5 MONTHLY PAYMENT: 101
YEAR: 1 BALANCE: 4152 TOTAL PAYMENT: 1216
YEAR: 2 BALANCE: 3235 TOTAL PAYMENT: 2433
YEAR: 3 BALANCE: 2241 TOTAL PAYMENT: 3649
YEAR: 4 BALANCE: 1165 TOTAL PAYMENT: 4866
YEAR: 5 BALANCE: 0 TOTAL PAYMENT: 6082
The issue is with your indentation, you put vaam function under loan function.
Python Learner. Working on a recurring monthly deposit, interest problem. Except I am being asked to build in a raise after every 6th month in this hypothetical. I am reaching the goal amount in fewer months than I'm supposed to.
Currently using the % function along with += function
annual_salary = float(input("What is your expected Income? "))
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment= total_cost*.25
savings = 0
for i in range(300):
savings = monthly_savings*(((1+.04/12)**i) - 1)/(.04/12)
if float(savings) >= down_payment:
break
if i % 6 == 0 :
monthly_salary += monthly_salary * .03
monthly_savings = monthly_salary * portion_saved
Thanks for the advice all. My code is getting clearer and I reached correct outputs! The problem was with how and when I was calculating interest. In the case of a static contribution I successfully used the formula for interest on a recurring deposit, here, the simpler move of calculating interest at each month was needed to work with the flow of the loop.
annual_salary = float(input("What is your expected Income? "))
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment = total_cost*.25
savings = 0
month = 1
while savings < down_payment :
print(savings)
savings += monthly_savings
savings = savings * (1+(.04/12))
month += 1
if month % 6 == 0 :
monthly_salary += (monthly_salary * semi_annual_raise)
monthly_savings = (monthly_salary * portion_saved)
print("")
print("it will take " + str(month) + " months to meet your savings goal.")
Does something like this work for you? Typically, we want to use while loops over for loops when we don't know how many iterations the loop will ultimately need.
monthly_savings = 1.1 # saving 10% each month
monthly_salary = 5000
down_payment = 2500
interest = .02
savings = 0
months = 0
while savings < goal:
print(savings)
savings = (monthly_salary * monthly_savings) + (savings * interest)
months += 1
if months % 6 == 0 :
monthly_salary += monthly_salary * .03
print("Took " + str(months) + " to save enough")
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)
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 -------------^
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))