Python loan table trouble - python

I'm currently trying to figure out how to iterate over over columns and rows at the same time [if possible]. Or wondering what the best way to approach this is. The biggest problem that I'm having is creating for loops with floats in simple ways. Our professor specifically asks for us to do that and then when we have to fill out the rest of the information basically accessing those loops. He doesn't want us to be importing different libraries and says there are simple ways for us to do this but doesn't really gives us guidance :/ Our table is supposed to be formatted to look like this:
this is what i have in total already..
Supporting Code:
def main():
print("This program is used to analyze commercial real estate loans.")
#function variables
purchase_price = input("Please input original purchase price: ")
down_payment = input("Please input total down payment: ")
APR = float(input("Please input APR: "))
periods_year = input("Please input the number of payments per year: ")
term = float(input("Please input loan length in years: "))
first_payment = input("Please input date of first payment in form MM/DD/YYYY: ")
#seperating str
dates = first_payment.split('/')
day = int(dates[0])
month = int(dates[1])
year = int(dates[2])
#part 1 calculations with main variables
total_payments = float(term) * float(down_payment)
loan_amount = float(purchase_price) - float(down_payment)
total_amount = loanCalc(APR, periods_year, loan_amount, total_payments)
end_date = str(day) + "/" + str(month) + "/" + str(year + int(term))
total_interest = r*total_payments
#print("End day of loan : %s" %end_date) [do not need to print this right now]
#loancalc function
def loanCalc(APR, period_year, loan_amount, total_payments):
#interest charged per period
r = (APR)/(period_year)
#amount paid in each period
P = (r * loan_amount)/(1- (1+r) ** (-(total_payments)))
#amount paid over life of loan
final_value = (P * total_payments)
#remember to return not print
return final_value
Code that needs a loop
#loan payment table part 3/table will display
def pmtOptions(APR,period_year, term,loan_amount):
#headers, each column will be 10
print("{0:^80}".format("Alternative Loan Payment Table"))
print("{0:^80}".format("=============================="))
print("{0:^80}".format("Interest Rates"))
#interest rate loop
##for APR in range(3,6):
## if APR == 3:
## print("3.25",)
## APR = 3.25
## while APR <= 5.75:
## APR +=.5
## print("{0:>3}".format(""),"{0:<3}".format(APR), end="")
#printing interest rate loop
print("{0:>10}".format(""),"{0:>10}".format("3.25%"),"{0:>10}".format("3.75%"),
"{0:>10}".format("4.25%"),"{0:>10}".format("4.75%"),"{0:>10}".format("5.25%"),
"{0:>10}".format("5.75%"),"{0:>10}".format("6.25%"))
#never ending column headings
print("{0:>10}".format("# Payments"),"{0:>10}".format("="*len("3.25%")),"{0:>10}".format("="*len("3.75%")),
"{0:>10}".format("="*len("4.25%")),"{0:>10}".format("="*len("4.75%")),"{0:>10}".format("="*len("5.25%")),
"{0:>10}".format("="*len("5.75%")),"{0:>10}".format("="*len("6.25%")))
#attempting calculations
#payments column
for term in range(12,37,6):
print("{0:^10}".format(term))
#column 1
for term in range(12,37,6):

Related

Why is my program outputting 178 instead of 183?"

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)
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).
Expected case
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
My code text output
Number of months = 178
r = 0.04
current_savings = 0
potion_down_payment = 0.25
annual_salary = input('Enter your annual salary: ')
print(int(annual_salary))
monthly_salary = (int(annual_salary) / 12)
potion_saved = input('Enter the percent of your salary to save, as a decimal: ')
print(float(potion_saved))
cost_dream_home = input('Enter the cost of your dream home : ')
print(int(cost_dream_home))
invest_return = ((float(r) * float(annual_salary)) / 12)
amount_to_save = (float(potion_down_payment) * int(cost_dream_home))
potion_saved_f = (float(monthly_salary) * float(potion_saved))
total_saved = (float(invest_return) + potion_saved_f)
number_of_months = (float(amount_to_save) // float(total_saved))
print(int(number_of_months))
I did this quickly, but you need a while loop, like:
months = 0
target = 250000
monthly_save = 1000.0
saved = 0.0
rate = .04
subtotal = 0.0
while subtotal < target:
saved += monthly_save
subtotal = (subtotal + monthly_save) * (1+(rate/12))
months += 1
print(months), print(int(subtotal))
OK, I have more time now. I think that you are just lucky that your code came out so close to the expected answer because your computations are off base. Unless you know of a better formula, you really need a loop in order to compute compound interest month by month. I have analyzed your method below.
invest_return = ((float(r) * float(annual_salary)) / 12) #.04*120000/12=400
amount_to_save = (float(potion_down_payment) * int(cost_dream_home))#.25*1000000=250000
potion_saved_f = (float(monthly_salary) * float(potion_saved))#10000*.1=1000
total_saved = (float(invest_return) + potion_saved_f) #400+1000
number_of_months = (float(amount_to_save) // float(total_saved)) #250000//1400 = 178
print(int(number_of_months))

Calculation of wage based on inputs in python

I have a python problem and I can't seem to get to the finish line with this question for homework. Basically, the problem is:
an employee's wage is $36.25p/h. a normal working week is 37 hours.
if he works more than 37 hours he gets paid 1.5 times the normal rate ($54.375)
if the employee sells 6 cars or more a week he receives a bonus of $200 per car sold.
TASK: Write a program that takes as input the number of hours worked and the total number of cars sold for the week, and outputs the car dealer’s total salary for the week.
Here is the code I have so far:
hours = int(input("How many hours were worked?"))
salary = float(input("The salary"))
cars = int(input("Total number of cars sold for the week?"))
total = hours * float(salary)
if hours > 37 and cars > 5:
print("The salary is:",int(cars) * int(200) / 10 + 1.5 * total )
elif hours <= 37:
print("The salary is:",total)
try this:
BASE_HOURS = 37
WAGE_MULTIPLIER = 1.5
CAR_SALES_BONUS = 200
BASE_WAGE_SALES = 5 # Updated after assignment adjustment in comments.
hours = int(input("How many hours were worked? > "))
wage = float(input("The wage > "))
cars = int(input("Total number of cars sold for the week? > "))
if hours > 37:
total = BASE_HOURS * wage + (hours - BASE_HOURS) * (wage * WAGE_MULTIPLIER)
else:
total = hours * wage
if cars > BASE_WAGE_SALES:
total += CAR_SALES_BONUS * (cars - BASE_WAGE_SALES)
# ...
As you can see I took my freedom to refactor the code quite a bit to improve structure & reduce code smell. Furthermore some variable names like salary where quite unfitting if I've interpreted the sense behind the script correctly, as we're interested in the hourly wage of the person, not his salary.

Building a calculator with set of input values and fixed interest rate

Assuming, I am running a weekly business and making profits every week at a constant interest rate of 5% per week and assuming my investment is recursive every week, I want to print all values for first 21 weeks. How do i right a code in python to achieve this?
Note: Investment is recursive, (i.e) every week my investment will be previous investment plus profit made in that week and also I am my rounding off the values and I have written this code but For loop I am struggling to write the logic , could some one help please. I have written the logic /calculations in excel - please check for expected results the excel screenshot.
maximum_number_of_weeks = int(input("maximum_number_of_weeks:"))
Initial_investment_Amount = int(input("Enter Initial Investment Amount Value ($) : "))
Interest_rate = float(input("Enter Interest Rate Value (%) : "))
Amount_Earned = Initial_investment_Amount * Interest_rate
Total_Amount_at_Disposal = Initial_investment_Amount + Amount_Earned
print("Total_Amount_at_Disposal ($) : ",Total_Amount_at_Disposal)
I suggest using a more simple approach:
Amount at disposal = Initial investment * (1 + interest rate) ^ (number of weeks)
maximum_number_of_weeks = int(input("maximum_number_of_weeks:"))
Initial_investment_Amount = int(input("Enter Initial Investment Amount Value ($) : "))
Interest_rate = float(input("Enter Interest Rate Value (%) : "))
for week in range(1, maximum_number_of_weeks + 1):
Total_Amount_at_Disposal = Initial_investment_Amount * (1 + Interest_rate/100) ** week
print("Total_Amount_at_Disposal ($) : ",round(Total_Amount_at_Disposal, 2))

program for loan amount and loan period

Write a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 3% to 5%, with an increment of 1/8. The formula of calculating the monthly payment and total payment are as follows:
I need help with the increment of 1/8. I've thought of a for loop but Python does not allow floats. I researched a bit and found something called numpy, but I haven't learned that yet. Is there a way to do it?
Here is what I have so far:
monthlyPay = 0
total = 0
#Prompt the user to enter loan amount and loan period in years
loanAmount = float(input("Enter loan amount: $"))
years = int(input("Enter loan period in years: "))
#Display Table Header
print("Interest\tMonthly Pay\tTotal")
#Display Table Results
for yr in range(0,years):
interestRate = 3/(100*12)
#Calculate Monthly Payment
monthlyPay = loanAmount*interestRate/(1-(1/((1+interestRate)**(years*12))))
#Calculate Total Payment
total = monthlyPay * years * 12
print(format(interestRate, '.3f'), '%\t\t', format(monthlyPay, '.2f'),\
'\t\t', format(total, '.2f'), sep = '')
I'm not sure about how to calculate the values you need, but from what I understand is that you need the interest rate to be starting with 3% and increase every year with 1/8, which is 0.125, and stops at five. If this is the case, numPy would be helpful. You could make interestRate as an array like this:
import numpy as np
interestRate = np.arange(3, 3 + 0.125*years, 0.125).clip(max=5)
arange gives an array of your need and clip makes all the values above 5 be equal to 5.

Python "format" syntax error

#Get the user's name.
Name = input('Enter your name.')
#Get number of stocks purchased.
Stocks_P = int(input('Enter the number of stocks purchased.'))
#Get purchase price of stocks.
Price_P = float(input('Enter the price of stocks purchased.'))
#Calculate total price.
Total_price = Stocks_P * Price_P
#Calculate Commission.
Com1 = Total_price * 0.03
#Calculate Cost.
Cost = Com1 + Total_price
#Get number of stocks sold.
Stocks_S = int(input('Enter the number of stocks sold.'))
#Get sale price of stocks.
Price_S = float(input('Enter the sale price of stocks.'))
#Calculate sale.
Sale = Stocks_S * Price_S
#Calculate sale Commission.
Com2 = Sale * 0.03
#Calculate profit or loss.
Profit = Sale - (Cost + Com2)
print('Your end total is: $' format(Profit, ',.2f') Name, sep='')
that's what i'm using for my first assignment in my python class, and in the last line, anything after the "print('You end total is: $' returns a syntax error no matter how i change it.
Indeed, just listing a string, a format() call and a variable name in a row is not valid Python syntax.
Either pass those three things in as separate arguments, using commas, or create a str.format() template for the values to be interpolated into:
print('Your end total is: $', format(Profit, ',.2f'), Name, sep='')
or
print('Your end total is: ${:,.2f}{}'.format(Profit, Name))

Categories