I am trying to write a program that will calculate the future value of a monthly investment. Here is what I have so far:
def get_number(prompt, low, high):
while True:
number = float(input(prompt))
if number > low and number <= high:
is_valid = True
return number
else:
print("Entry must be greater than", low,
"and less than or equal to", high,
"Please try again.")
def get_integer(prompt, low, high):
while True:
number = int(input(prompt))
if number > low and number <= high:
is_valid = True
return number
else:
print("Entry must be greater than", low,
"and less than or equal to", high,
"Please try again.")
def calculate_future_value(monthly_investment, yearly_interest, years):
# convert yearly values to monthly values
monthly_interest_rate = ((yearly_interest / 100) + 1) ** (1 / 12)
months = years * 12
# calculate future value
future_value = 0.0
for i in range(1, months):
future_value += monthly_investment
monthly_interest = (future_value * monthly_interest_rate)-future_value
future_value += monthly_interest
return future_value
def main():
choice = "y"
while choice.lower() == "y":
# get input from the user
monthly_investment = get_number("Enter monthly investment:\t", 0, 1000)
yearly_interest_rate = get_number("Enter yearly interest rate:\t", 0, 15)
years = get_integer("Enter number of years:\t\t", 0, 50)
# get and display future value
future_value = calculate_future_value(
monthly_investment, yearly_interest_rate, years)
print("Future value:\t\t\t" + str(round(future_value, 2)))
# see if the user wants to continue
choice = input("Continue? (y/n): ")
print("Bye!")
if __name__ == "__main__":
main()
Everything in the program is working fine except for the def calculate_future_value(monthly_investment, yearly_interest, years): section I believe I have a logic error but I can't find exactly what's going wrong.
The output should look like this
Enter monthly investment: 350
Enter yearly interest rate: 10
Enter number of years: 36
Future value: 1484636.15
Continue? (y/n): n
Bye!
But im getting
Enter monthly investment: 350
Enter yearly interest rate: 10
Enter number of years: 36
Future value: 1312573.73
Continue? (y/n): no
Bye!
In testing out your code, I believe you really only need to correct one formula. The following statement does not appear to be correct.
monthly_interest_rate = ((yearly_interest / 100) + 1) ** (1 / 12)
That would appear to raise your yearly interest rate to the "1/12th" power and not divide it into 1/12th of the yearly interest. I revised that formula as follows:
monthly_interest_rate = ((yearly_interest / 12 / 100) + 1)
When I ran the program the value came out close to what you noted in your issue.
#Dev:~/Python_Programs/Investment$ python3 Invest.py
Enter monthly investment: 350
Enter yearly interest rate: 10
Enter number of years: 36
Future value: 1472016.43
Continue? (y/n): n
Bye!
The difference between this value and the value you stated might be attributable to actually having the interest compounded daily each month.
But you might give this tweak a try and see if it meets the spirit of your project.
Related
I'm trying to build a loan calculator that takes in the amount owed and interest rate per month and the down payment put at the beginning and the monthly installments so it can output how many months do you need to pay off your debt. The program works just fine when I enter an interest_rate below 10% but if I type any number for example 18% it just freezes and gives no output. When I stop running the program it gives me these errors:
Traceback (most recent call last):
File "C:\Users\Khaled\PycharmProjects\interest_payment\main.py", line 35, in <module>
months_to_finish = get_months(price) # this returns the number of months from the counter var
File "C:\Users\Khaled\PycharmProjects\interest_payment\main.py", line 6, in get_months
price = price - installments
KeyboardInterrupt
This is my code:
def get_months(price):
counter = 0
price = price - down_payment
while price > 0:
price = price + price * interest_rate
price = price - installments
counter += 1
return counter
if __name__ == '__main__':
price = float(input("Enter price here: "))
interest_rate = float(input("Enter interest rate here: %")) / 100
while interest_rate < 0:
interest_rate = float(input('Invalid interest rate please try again: %')) / 100
down_payment = int(input("Enter your down payment here: $"))
while down_payment > price or down_payment < 0:
down_payment = int(input('Invalid down payment please try again: $'))
choice = input("Decision based on Installments (i) or Months to finish (m), please write i or m: ").lower()
if choice == 'm':
print('m')
elif choice == 'i':
installments = int(input("What's your monthly installment budget: ")) # get the installments
months_to_finish = get_months(price) # this returns the number of months from the counter var
print(f"It will take {months_to_finish} months to finish your purchase.")
else:
print('Invalid choice program ended')
These are the test values:
Enter price here: 22500
Enter interest rate here: %18
Enter your down payment here: $0
Decision based on Installments (i) or Months to finish (m), please write i or m: i
What's your monthly installment budget: 3000
With an initial principal of $22,500, an interest rate of 18%, a down payment of $0, and a monthly payment of $3,000, it will take an infinite number of months to pay off the loan. After one period at 18% interest, you have accrued $4,050 of interest. Since you're only paying $3,000 per period, you're not even covering the amount of new interest, and the total amount you owe will grow forever. You probably want to check somewhere that the monthly payment is greater than the first month's interest. You could modify your code like this:
if installments < (price - down_payment) * interest_rate:
print("The purchase cannot be made with these amounts.")
else:
months_to_finish = get_months(price)
print(f"It will take {months_to_finish} months to finish your purchase.")
l=[]
n=int(input())
i=0
for i in range(n):
l.append(str(input()))
def long(x):
if x>10:
return print(l[i][0]+str(len(l[i])-2)+l[i][-1])
def short(x):
if x<=10:
return print(l[i])
i=0
for i in range(len(l[i])):
long(len(l[i]))
short(len(l[i]))
continue
I am trying to execute a function that will repeat if given the right input as seen in my while statement. However my program returns the same value in additional loops without option to use new hrs and rate inputs if my input statements are above my function. If they are within the function as currently presented, it states my (hrs,rate) is not defined. How would I define the hrs and rate parameters while keeping my inputs within the function?
def CalPay(hrs,rate):
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
try:
hrs = float(hrs)
except:
hrs = -1
try:
rate = float(rate)
except:
rate = -1
if hrs <= 0 :
print('You have entered wrong information for hours.')
elif rate <= 0 :
print('You have entered wrong rate information.')
elif hrs <= 40 :
pay = hrs * rate
print ('Your pay for this week is:', pay)
elif hrs > 40 and hrs < 60 :
pay = ((hrs - 40) * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
elif hrs >= 60 :
pay = ((hrs - 60) * (rate * 2.0)) + (20 * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
while True:
CalPay(hrs,rate)
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
First, you need to initialize the two variables after the function, so whenever the time you enter the variables' values, they've to be defined.
Something like that:
# those two lines will be after the function
hrs = 0
rate = 0
Full program will go like that: -
def CalPay(hrs,rate):
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
try:
hrs = float(hrs)
except:
hrs = -1
try:
rate = float(rate)
except:
rate = -1
if hrs <= 0 :
print('You have entered wrong information for hours.')
elif rate <= 0 :
print('You have entered wrong rate information.')
elif hrs <= 40 :
pay = hrs * rate
print ('Your pay for this week is:', pay)
elif hrs > 40 and hrs < 60 :
pay = ((hrs - 40) * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
elif hrs >= 60 :
pay = ((hrs - 60) * (rate * 2.0)) + (20 * (rate * 1.5)) + (40 * rate)
print ('Your pay for this week is:', pay)
hrs = 0
rate = 0
while True:
CalPay(hrs,rate)
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
OUTPUT
Please enter number of hours worked for this week: 36
What is hourly rate: 6
Your pay for this week is: 216.0
Do you wish to repeat this program? (y/n)Y
Please enter number of hours worked for this week: 12
What is hourly rate: 5
Your pay for this week is: 60.0
Do you wish to repeat this program? (y/n)
In your while loop you call CalPay and pass in hrs and rate. You are calling a function and giving it two values that you create inside of the function i.e. they don't exist when you call CalPay, so you get an error. Just collect the inputs in your while loop instead of inside your function. Like this:
while True:
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
CalPay(hrs,rate)
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
Note: You'll have to adjust the logic for repeating the program accordingly.
Another even better solution would be to remove the arguments from CalPay and the function call and then collect the information you need inside the function. As mentioned by Anurag.
def CalPay():
hrs = input('Please enter number of hours worked for this week:')
rate = input('What is hourly rate:')
try:
hrs = float(hrs)
except:
.
.
.
while True:
CalPay()
yn = input('Do you wish to repeat this program? (y/n)').lower()
if yn == 'y' :
continue
if yn == 'n' :
break
print ('Done!')
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.
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 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