Unsure why output is 0. Trying to count months to pay downpayment - python

print("Please enter you starting annual salary: ")
annual_salary = float(input())
monthly_salary = annual_salary/12
print("Please enter your portion of salary to be saved: ")
portion_saved = float(input())
print ("Please enter the cost of your dream home: ")
total_cost = float(input())
current_savings = 0
r = 0.04/12
n = 0
portion_down_payment = total_cost*int(.25)
if current_savings < portion_down_payment:
monthly_savings = monthly_salary*portion_saved
interest = monthly_savings*r
current_savings = current_savings + monthly_savings + interest
n =+ 1
else:
print(n)
The above is my code. I keep getting output = 0 but unsure why.
This the problem statement, I am a HS student attempting OCW coursework.
Call the cost of your dream home ​total_cost​.
Call the portion of the cost needed for a down payment ​portion_down_payment​. For simplicity, assume that portion_down_payment = 0.25 (25%).
Call the amount that you have saved thus far ​current_savings​. You start with a current savings of $0.
Assume that you invest your current savings wisely, with an annual return of ​r ​(in other words, at the end of each month, you receive an additional ​current_savings*r/12​ funds to put into your savings – the 12 is because ​r​ is an annual rate). Assume that your investments earn a return of r = 0.04 (4%).
Assume your annual salary is ​annual_salary​.
Assume you are going to dedicate a certain amount of your salary each month to saving for the down payment. Call that ​portion_saved​. This variable should be in decimal form (i.e. 0.1 for 10%).
At the end of each month, your savings will be increased by the return on your investment, plus a percentage of your ​monthly salary ​(annual salary / 12). Write a program to calculate how many months it will take you to save up enough money for a down payment. You will want your main variables to be floats, so you should cast user inputs to floats.
Your program should ask the user to enter the following variables:
The starting annual salary (annual_salary)
The portion of salary to be saved (portion_saved)
The cost of your dream home (total_cost)
Test Case 1
Enter your annual salary:​ 120000 Enter the percent of your salary to save, as a decimal:​ .10 Enter the cost of your dream home:​ 1000000 Number of months:​ 183

You have n =+ 1 but I think you mean n += 1
Also int(.25) evaluates to 0, I think you want int(total_cost*.25). As your code is, the if statement will always evaluate to False because current_savings == 0 and portion_down_payment == 0
More generally, when your code isn't working as expected, you should put in either print() or assert statements to narrow down where your code is deviating from what you expect. For example, before the if statement you could have it print the two values you are comparing.

Related

Removing the loops (for, while) in Python

There is a code that calculates after how many years the deposit amount will reach the target amount, taking into account the specified interest rate (the fractional part is discarded).
deposit_amount = int(input('Input deposit amount: '))
annual_percentage = int(input('input annual percentage: '))
final_amount = int(input('Input final amount: '))
year = 0
while deposit_amount < final_amount:
year += 1
deposit_amount = deposit_amount * (100 + annual_percentage) // 100
print('After', year, 'years the amount will be:', deposit_amount)
Question: How to solve the same problem without using cycles? They gave a hint that you can use the "math" library.
Julien and accdias thank you!
Everything would be fine, but according to the condition of the problem, the answer should not be the sum, after n the number of periods, but the number of periods (n). While studying compound interest, I came across logarithms and solved the problem using them using the math library. Most likely, my teacher meant exactly this decision:
deposit_amount = int(input('Input deposit amount: '))
annual_percentage = int(input('input annual percentage: '))
final_amount = int(input('Input final amount: '))
years = ceil(log(final_amount / deposit_amount, annual_percentage))
print('After', years, 'years, your investments will reach the goal and amount to',
round(deposit_amount * annual_percentage**years), 'coins.')

Calculation error at runtime in python loan calculator

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

Modification of Future Value

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.

Python CD annual precentage

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

Python Bisection search overshoots target

I have to create a code to find the exact payment, to the cent, needed to pay off a loan in 12 months using bisection. The code I created for this works but it overshoots it's target. The loan will be payed off within the 12 months but after making 12 payments the final balance should be around 0. However it is a way bigger negative number.
The code I am using is:
StartBalance = float(raw_input('Credit Balance in $: '))
AnnualRate = float(raw_input('Annual interest rate in decimals: '))
MonthlyRate = AnnualRate / 12.0
MinPaymentLow = StartBalance / 12.0
MinPaymentHigh = (StartBalance*(1+MonthlyRate)**12.0)/12.0
cent = 0.01
Payment = (MinPaymentHigh+MinPaymentLow)/2.0
while (Payment*12-StartBalance) >= cent:
for month in range(0, 12):
Balance = (StartBalance-Payment)/10*(1+MonthlyRate)
if Balance < 0:
MinPaymentLow = Payment
elif Balance > 0:
MinPaymentHigh = Payment
Payment = (MinPaymentHigh + MinPaymentLow)/ 2.0
print 'RESULT'
print 'Number of months needed: 12'
print 'Montly pay: $', round(Balance,2)
It looks like these lines:
for month in range(0, 12):
Balance = (StartBalance-Payment)/10*(1+MonthlyRate)
Should be:
Balance = StartBalance
for month in range(0, 12):
Balance = (Balance-Payment) * (1 + MonthlyRate)
Or something similar, depending on how you want to calculate interest, and whether you consider payments occurring at the start or end of the month.
Your code seemed to work fine for me, but if you're getting results that are "way off" it's probably because you're using the float datatype. Float is untrustable, because it rounds on every operation. Given enough iterations and you've rounded off a lot of money. Try using decimal instead. This module keeps track of decimals as indexed integer values.

Categories