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
Related
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.
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.
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.')
How to make it right1
How to put like this maximum and minimum gross pay and number
you can create a list of gross_pays and you can get the maximum and minimum from the list
NUM_EMPLOYEES = int(input('Enter number of employees : '))
def main():
hours = []
number = 1
for index in range (NUM_EMPLOYEES):
employee = int(input(f"Enter the hours worked by employee {number}:"))
number += 1
hours.append(employee)
pay_rate= float (input("Enter the hourly pay rate : "))
number = 1
gross_pay2 = []
for index in hours:
gross_pay = index * pay_rate
print (f"Goss pay for employee {number}: ${gross_pay}")
gross_pay2.append(gross_pay)
number += 1
maximum=gross_pay2.index(max(gross_pay2))+1
minimum=gross_pay2.index(min(gross_pay2))+1
print(f'Employee {maximum} gets maximum gross pay: {max(gross_pay2)}')
print(f'Employee {minimum} gets minimum gross pay: {min(gross_pay2)}')
main()
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.