I have to write a program showing the total number of payments and total amount paid for a mortgage. The problem assumes an extra $1000 a month for the first 12 months. The answer $929,965.62 over 342 months. The output I get is $929,965.62 over 343 months. The problem is my code starts counting at 2 but the first amount is correct.
principal = 500000.0
rate = 0.05
payment = 2684.11
total_paid = 0.0
extra_payment = 1000
payment_number = 1
while principal > 0 and payment_number <=12:
principal = principal * (1+rate/12) - (payment + extra_payment)
total_paid = total_paid + (payment + extra_payment)
payment_number += 1
print(payment_number, round(total_paid, 2))
else:
while principal > 0:
principal = principal * (1+rate/12) - payment
total_paid = total_paid + payment
payment_number += 1
print(payment_number, round(total_paid, 2))
I don't understand why the above code starts at 2 and the code below starts counting at 1.
height = 100
bounce = 1
while bounce <= 10:
height = height * (3/5)
print(bounce, round(height, 4))
bounce += 1
First example you print after you increment payment_number; second sample it's reversed. Change
payment_number += 1
print(payment_number, round(total_paid, 2))
to
print(payment_number, round(total_paid, 2))
payment_number += 1
Related
What's different between lines 16 and 17?
#user input
annual_salary = float(input("Enter your annual salary: "))
portion_saved = float(input("Enter the percent of your salary to save, as a decimal: "))
total_cost = float(input("Enter the cost of your dream home: "))
#static vars
portion_down_payment = total_cost*.25
monthly_salary = annual_salary/12
r = .04 #annual rate of return
months_to_save = 0
current_savings = 0
investment_return = current_savings * r / 12
while current_savings < portion_down_payment:
#current_savings += (current_savings * r / 12) + (portion_saved * monthly_salary) # Line 16
current_savings += (investment_return) + (portion_saved*monthly_salary) # Line 17
months_to_save += 1
print("Number of months: ", months_to_save)
I tried running it through pythontutor and the variation happens on step 15 of execution, but I can't quite figure out what's different.
When you use current_savings += investment_return, it adds the same amount of interest to current_savings each time through the loop. That interest is equal to current_savings * r / 12 calculated before you started the loop.
But when you use current_savings += (current_savings * r / 12), you recalculate the interest each time through the loop. So the interest is calculated based on the current value of current_savings, which gets bigger each time the loop runs.
In other words, the first one calculates simple interest, and the second one calculates compound interest.
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 am trying to write a Python program that charges the parking fee for how many hours you have parked.
Everything works fine until the minutes exceed 300.
I have played with returns and every time I did that after the input I would get successful completion no output.
When I put in 600 minutes (10 hours) I get a fee of 40 dollars when it should be 30 dollars.
Here is my code:
import math
rate1 = 5
rate2 = 4
rate3 = 3
m = int(input('Please enter the number of minutes parked: '))
if m <= 60:
x = m/60
fee = math.ceil(x) * 5
print('Parking fee for',m,'minutes is $',fee)
elif m>60 & m<=300:
x = m/60
fee = math.ceil(x) * rate2
print('Parking fee for',m,'minutes is $',fee)
elif m>300:
x = m/60
fee = math.ceil(x) * rate3
print('Parking fee for',m,'minutes is $',fee)
else:
print('Invalid input')
output:
Please enter the number of minutes parked: 600
Parking fee for 600 minutes is $ 40
Process finished with exit code 0
if m > 60 & m <= 300:
should be:
if m > 60 and m <= 300:
or
if 60 < m <= 300:
& is the bit-wise AND operator, and is the logical AND operator (this is analogous to the difference between & and && in C, PHP, and Javascript).
I've been looking at this program for a while now and I can't seem to find what is wrong with the code. I've checked the numbers and they are fine. I almost think its a quotes or parentheses. I would appreciate the help. Here's the code:
# step 1: get the input
timbitsLeft = int(input())
# step 2: initialize the total cost
totalCost = 0
# step 3: buy as many large boxes as you can
bigBoxes = int(timbitsLeft / 40)
totalCost = totalCost + bigBoxes * 6.19 # update the total price
timbitsLeft = timbitsLeft - 40 * bigBoxes # calculate timbits still needed
# step 4, can we buy a medium box?
if timbitsLeft >= 20:
totalCost = totalCost + 3.39
timbitsLeft = timbitsLeft - 20
if timbitsLeft > 10: # step 5, can we buy a small box?
totalCost = totalCost + 1.99
timbitsLeft = timbitsLeft - 20
# step 6
totalCost = totalCost + timbitsLeft * 20
print(totalCost)
This is the error I get:
Did not pass tests. Please check details below and try again.
Results for test case 1 out of 11
Input:
10
Program executed without crashing.
Program output:
200.0
Expected this correct output:
1.99
Result of grading: Output line 1, value 200.0, did not match expected value 1.99
You are getting an output of 200 because you do not have enough money to buy a large box or medium box. You then check to see if you can buy a small box, but you only have 10 timbits, so the if statement, if timbitsLeft > 10: # step 5, can we buy a small box?, is not true so you cannot buy a small box either. Then you do the calculation totalCost = totalCost + timbitsLeft * 20 which gives you a value of 200.
Well, looks like your mistake is
if timbitsLeft > 10:
Your input is 10 so you have 10 timbits left,
but you need more than 10 to go further into the if statement,
therefore its not doing anything except:
totalCost = totalCost + timbitsLeft * 20
and thats basically
totalCost = 0 + 10 * 20
and that is indeed 200
you might need
if timbitsLeft >= 10:
You didn't read all of the information given to you.
The numbers are wrong for the small box and the price of 1 box.
if timbitsLeft > 10: # step 5, can we buy a small box?
totalCost = totalCost + 1.99
timbitsLeft = timbitsLeft - 20 (<---- the problem. it should be: - 10)
-10 is the amount of small boxes.
totalCost = totalCost + timbitsLeft * 20 (<---- the problem. it should be: *.2)
print(totalCost)
.2 is the price of a single box.
here is the solution to the cscircles "Coding Exercise: Timbits"
timbitsLeft = int(input()) # step 1: get the input
totalCost = 0 # step 2: initialize the total cost
# step 3: buy as many large boxes as you can
if timbitsLeft >=40:
bigBoxes = int(timbitsLeft / 40)
totalCost = totalCost + bigBoxes * 6.19 # update the total price
timbitsLeft = timbitsLeft - 40 * bigBoxes # calculate timbits still needed
if timbitsLeft >= 20: # step 4, can we buy a medium box?
mediumBoxes = int(timbitsLeft / 20)
totalCost = totalCost + mediumBoxes * 3.39
timbitsLeft = timbitsLeft - 20 * mediumBoxes
if timbitsLeft >= 10: # step 5, can we buy a small box?
smallBoxes = int(timbitsLeft / 10)
totalCost = totalCost + smallBoxes*1.99
timbitsLeft = timbitsLeft - smallBoxes*10
totalCost = totalCost + timbitsLeft * 0.2 # step 6
print(totalCost) # step 7
Now write a program that calculates the minimum fixed monthly payment needed in order pay off a credit card balance within 12 months. By a fixed monthly payment, we mean a single number which does not change each month, but instead is a constant amount that will be paid each month.
In this problem, we will not be dealing with a minimum monthly payment rate.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
The program should print out one line: the lowest monthly payment that will pay off all debt in under 1 year, for example:
Lowest Payment: 180
Assume that the interest is compounded monthly according to the balance at the end of the month (after the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme, which is okay. A summary of the required math is found below:
Monthly interest rate = (Annual interest rate) / 12.0
Monthly unpaid balance = (Previous balance) - (Minimum fixed monthly payment)
Updated balance each month = (Monthly unpaid balance) + (Monthly interest rate x Monthly unpaid balance)
Here is my code. I do not know where I'm going wrong:
balance = float(raw_input('enter the outsanding balance on your card'))
annualInterestRate = float(raw_input('enter the anual interest rate as a decimal'))
month = 0
checkBalance = balance
monthlyFixedPayment = 0
while checkBalance <= 0:
checkBalance = balance
monthlyFixedPayment += 10
while month <= 11:
monthlyInterestRate = annualInterestRate/12.0
monthlyUnpaidBalance = checkBalance - monthlyFixedPayment
checkBalance = monthlyUnpaidBalance + (monthlyInterestRate * monthlyUnpaidBalance)
print('lowest payment:' + str(monthlyFixedPayment))
I think this is the program you are looking for:
balance = 500
annualInterestRate = .5
checkBalance = balance
monthlyFixedPayment = 10
count = 0
while checkBalance > 0:
month = 0
while month <= 11 and checkBalance > 0:
count+=1
monthlyInterestRate = annualInterestRate/12.0
monthlyUnpaidBalance = checkBalance - monthlyFixedPayment
checkBalance = monthlyUnpaidBalance - (monthlyInterestRate * monthlyUnpaidBalance)
print "\t"+str(checkBalance)
month+=1
print checkBalance
print "lowest amount: "
print count*monthlyFixedPayment+checkBalance
I have left the print statements, so that you can see what is going on in each iteration.
Some problems i noticed in your code:
1) you were doing a monthlyFixedPayment += 10 that was changing the fixed payemnt. you are not supposed to change the fixed payment according to your problem definition.
2) you were doing a checkBalance = balance in each iteration of outer while loop. This was causing the calculated value to be resetted.
3) I have introduced a count variable to check how many times these decuctions were happening, as month was getting reset in each iteration.
while checkBalance <= 0: to while checkBalance >= 0:
Also, you need to increment month in the while month <= 11: loop.
You are going at it the hard way; there is an analytic solution for fixed_payment:
from math import ceil
def find_fixed_monthly_payment(balance, months, yearly_rate):
i = 1. + yearly_rate / 12.
im = i ** months
return balance * (im * (1. - i)) / (i * (1. - im))
def find_final_balance(balance, months, yearly_rate, fixed_payment):
i = 1. + yearly_rate / 12.
for _ in range(months):
# make payment
balance -= fixed_payment
# add interest
balance *= i
return balance
def get_float(prompt):
while True:
try:
return float(raw_input(prompt))
except ValueError:
# input could not be cast to float; try again
pass
def main():
balance = get_float("Please enter starting balance: ")
annual_rate = get_float("Annual interest rate (in percent): ") / 100.
fixed_payment = find_fixed_monthly_payment(balance, 12, annual_rate)
# round up to the nearest $10
fixed_payment = ceil(fixed_payment / 10.) * 10.
# double-check value of fixed_payment:
assert find_final_balance(balance, 12, annual_rate, fixed_payment ) <= 0., "fixed_payment is too low!"
assert find_final_balance(balance, 12, annual_rate, fixed_payment - 10.) > 0., "fixed_payment is too high!"
print("Lowest payment: ${:0.2f}".format(fixed_payment))
if __name__ == "__main__":
main()