Help me!! It's not justified (python)
# Accept the inputs
startBalance = float(input("Enter the investment amount: "))
years = int(input("Enter the number of years: "))
rate = int(input("Enter the rate as a %: "))
# Convert the rate to a decimal number
rate = rate / 100
# Initialize the accumulator for the interest
totalInterest = 0.0
# Display the header for the table V.3
print("%4s%18s%10s%16s" % \
("Year", "Starting balance",
"Interest", "Ending balance"))
# f string
# Compute and display the results for each year
for year in range(1, years + 1):
interest = startBalance * rate
endBalance = startBalance + interest
print(f"{year:>4}{startBalance:<18.2f}{interest:>10.2f}{endBalance:>16.2f}")
startBalance = endBalance
totalInterest += interest
# Display the totals for the period
print("Ending balance: $%0.2f" % endBalance)
print("Total interest earned: $%0.2f" % totalInterest)
I was trying to align data in a table on the right side of the column. I use f string and formatting type in the variable placeholder but there was no alignment.
I try to run the code on jupyter and VS Code.
There is no need to mix different template systems. Just use f-strings:
pv = float(input('Enter the investment amount: '))
years = range(int(input('Enter the number of years: ')))
rate = int(input('Enter the rate as a %: ')) / 100
interests = 0.0
print('Year Starting balance Interest Ending balance')
for year in years:
interest = pv * rate
fv = pv + interest
print(f'{year + 1:>4d}{pv:>17.2f}{interest:>10.2f}{fv:>16.2f}')
pv = fv
interests += interest
print(f'Ending balance: ${fv:0.2f}')
print(f'Total interest earned: ${interests:0.2f}')
And here is an example of the output:
Enter the investment amount: 200
Enter the number of years: 10
Enter the rate as a %: 15
Year Starting balance Interest Ending balance
1 200.00 30.00 230.00
2 230.00 34.50 264.50
3 264.50 39.67 304.18
4 304.18 45.63 349.80
5 349.80 52.47 402.27
6 402.27 60.34 462.61
7 462.61 69.39 532.00
8 532.00 79.80 611.80
9 611.80 91.77 703.58
10 703.58 105.54 809.11
Ending balance: $809.11
Total interest earned: $609.11
Related
*****UPDATE: Thanks to everyone who contributed. The code is alright. I figured there was a problem with the website I was using as IDLE.
I have to write a program in Python that calculates then prints specific information about a loan. The program (code below) consists of 2 functions and I have written them correctly. The only problem I have is that I have to write the second function within the first one. When I run the code, I get this error: NameError: name 'vaam' is not defined
I've just started coding last week, I hope you guys help me out with this.
Here's my program:
# Your function for calculating payment goes here
def loan(principal,annual_interest_rate,duration):
r=(annual_interest_rate)/1200
n=duration*12
if annual_interest_rate==0:
monthly_payment=principal/n
else:
monthly_payment=(principal*(r*(1+r)**n))/((1+r)**n-1)
return monthly_payment
# Your function for calculating remaining balance goes here
def vaam(principal, annual_interest_rate, duration , number_of_payments):
n=duration*12
r=(annual_interest_rate)/1200
if annual_interest_rate==0:
remaining_loan_balance=principal-principal*(number_of_payments/n)
else:
remaining_loan_balance=(principal*((1+r)**n-(1+r)**number_of_payments))/((1+r)**n-1)
return remaining_loan_balance
# Your main program goes here
principal=float(input("Enter loan amount: "))
annual_interest_rate=float(input("Enter annual interest rate (percent): "))
duration=int(input("Enter loan duration in years: "))
print('LOAN AMOUNT:',int(principal),'INTEREST RATE (PERCENT):',int(annual_interest_rate))
print('DURATION (YEARS):',int(duration),'MONTHLY PAYMENT:',int(loan(principal,annual_interest_rate,duration)))
for i in range(1,duration+1):
print('YEAR:',i,'BALANCE:',int(vaam(principal, annual_interest_rate, duration , i*12)),'TOTAL PAYMENT:',int(loan(principal,annual_interest_rate,duration)*12*i))
Try this:
# Your function for calculating payment goes here
def loan(principal, annual_interest_rate, duration):
r = (annual_interest_rate) / 1200
n = duration * 12
if annual_interest_rate == 0:
monthly_payment = principal / n
else:
monthly_payment = (principal * (r * (1 + r) ** n)) / ((1 + r) ** n - 1)
return monthly_payment
# Your function for calculating remaining balance goes here
def vaam(principal, annual_interest_rate, duration, number_of_payments):
n = duration * 12
r = (annual_interest_rate) / 1200
if annual_interest_rate == 0:
remaining_loan_balance = principal - principal * (number_of_payments / n)
else:
remaining_loan_balance = (principal * ((1 + r) ** n - (1 + r) ** number_of_payments)) / ((1 + r) ** n - 1)
return remaining_loan_balance
# Your main program goes here
principal = float(input("Enter loan amount: "))
annual_interest_rate = float(input("Enter annual interest rate (percent): "))
duration = int(input("Enter loan duration in years: "))
print('LOAN AMOUNT:', int(principal), 'INTEREST RATE (PERCENT):', int(annual_interest_rate))
print('DURATION (YEARS):', int(duration), 'MONTHLY PAYMENT:', int(loan(principal, annual_interest_rate, duration)))
for i in range(1, duration + 1):
print('YEAR:', i, 'BALANCE:', int(vaam(principal, annual_interest_rate, duration, i * 12)), 'TOTAL PAYMENT:',
int(loan(principal, annual_interest_rate, duration) * 12 * i))
Output
Enter loan amount: 5000
Enter annual interest rate (percent): 8
Enter loan duration in years: 5
LOAN AMOUNT: 5000 INTEREST RATE (PERCENT): 8
DURATION (YEARS): 5 MONTHLY PAYMENT: 101
YEAR: 1 BALANCE: 4152 TOTAL PAYMENT: 1216
YEAR: 2 BALANCE: 3235 TOTAL PAYMENT: 2433
YEAR: 3 BALANCE: 2241 TOTAL PAYMENT: 3649
YEAR: 4 BALANCE: 1165 TOTAL PAYMENT: 4866
YEAR: 5 BALANCE: 0 TOTAL PAYMENT: 6082
The issue is with your indentation, you put vaam function under loan function.
I have a working code
I have a working code, which gives the correct answer, however I cant figure out how to get it to print the amount for each year (for example if i enter 5yrs it will only give the amounts for the fifth year. I want it to print year 1, 2, 3 ,4 and 5 (print results for every year up to the entered year)
InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))
TotalInterestEarned = 0
for i in range(Years):
InterestEarned = round(InvestAmount*(Rate/100),2)
EndingBal = round(InvestAmount+InterestEarned , 2)
print("Starting Balance: $"+ str (InvestAmount))
print("Ending balance: $"+str(EndingBal))
print("Total Interest Earned: $"+str(InterestEarned))
This gonna help you
InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))
TotalInterestEarned = 0
for i in range(Years):
InterestEarned = round(InvestAmount*(Rate/100),2)
EndingBal = round(InvestAmount+InterestEarned , 2)
print(f"{i+1} year - Starting Balance: ${InvestAmount}")
print(f"{i+1} year - Ending balance: ${EndingBal}")
print(f"{i+1} year - Total Interest Earned: ${InterestEarned}")
Modify your for loop like this:
for i in range(Years):
InterestEarned = round(InvestAmount*(Rate/100),2)
EndingBal = round(InvestAmount+InterestEarned , 2)
print("Year" + i+1 + " Interest Earned: $" + InterestEarned)
print("Year" + i+1 + " Balance: $" + EndingBal)
Shift your print statements to the for loop and print i as well
for i in range(Years):
InterestEarned = round(InvestAmount*(Rate/100),2)
EndingBal = round(InvestAmount+InterestEarned , 2)
print("Starting Balance: for year " +(i+1)+"$"+str (InvestAmount))
print("Ending balance: for year" +(i+1)+"$"+str(EndingBal))
print("Total Interest Earned: for year" +(i+1)
+"$"+str(InterestEarned))
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")
so I'm trying to display salary with annual % increase for certain amount of years
print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())
calculation1 = ANNUAL_INCREASE / 100
calculation2 = calculation1 * SALARY
calculation3 = calculation2 + SALARY
Yearloops = int(input('Enter number of years: '))
for x in range(Yearloops):
print(x + 1, calculation3 )
This is my output so far by entering 25000 as salary, 3 as % increase and 5 for years.
1 25750.0
2 25750.0
3 25750.0
4 25750.0
5 25750.0
I need to multiply the last answer again by the % increase. Should be like this
1 25000.00
2 25750.00
3 26522.50
4 27318.17
5 28137.72
Can someone show me how to do it? Thanks.
You need to put your calculations inside your for loop so that it occurs every year instead of just once
salary = float(input('enter starting salary: '))
annual_increase = float(input('enter the annual % increase: '))
years = int(input('enter number of years: '))
for x in range(years):
print(x + 1, salary)
increase = (annual_increase/100) * salary
salary += increase
Entering 25000, 3%, and 5 years outputs
1 25000.0
2 25750.0
3 26522.5
4 27318.175
5 28137.72025
Adapting a bit your version of the code:
print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())
Yearloops = int(input('Enter number of years: '))
value = SALARY
for x in range(Yearloops):
print('{} {:.2f}'.format(x + 1, value))
value = value * (1 + ANNUAL_INCREASE/100)
This produces the following output with the test case 25000, 3, 5:
Enter the strting salary: 25000
Enter the annual % increase: 3
Enter number of years: 5
1 25000.00
2 25750.00
3 26522.50
4 27318.17
5 28137.72
I think this will do what you are looking for:
print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())
calculation1 = ANNUAL_INCREASE / 100
Yearloops = int(input('Enter number of years: '))
newsalary = SALARY
print(1, newsalary )
for x in range(1,Yearloops):
newsalary = newsalary*(1+calculation1)
print(x + 1, newsalary )
I printed the first year outside the loop since we don't want to calculate an increase yet, according to your spec.
This seems like a pretty straightforward solution to your problem. For your knowledge: it is common to use for _ in something when you aren't actually going to use the item you're iterating over.
print('Enter the starting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())
Yearloops = int(input('Enter number of years: '))
for _ in range(Yearloops):
print(SALARY)
SALARY += (SALARY / 100) * ANNUAL_INCREASE
I´m learning Python at one of my college classes and I was asked to create a "Loan Calculator".... I might have an idea but I´m not sure how to fix an error that I´m getting TypeError: 'float' object is not subscriptable
This is the announcement
The user has to enter the cost of the loan, interest rate and the number of years of the loan.
Calculate the monthly payments with the following formula:
M = L[i(1+i)^n]/[(1+i)^(n)-1]
Data:
M = monthly payment
L = loan amount
i = interest rate (remember that 5%, i = 0.05)
n = number of payments
And this is my code:
# Loan Calculator
# Equation: M = L[i(1+i)^n]/[(1+i)(n)-1]
print("Loan Calculator")
L = float(input("Loan amount: "))
i = float(input("Interest rate: "))
# Remember: 5% ---> i=0.05
n = float(input("Number of payments: "))
M = (L[i*(1+i)**n]/[(1+i)**(n)-1])
# M = Monthly payment
print("Monthly payment: " + M)
PS: I first thought I was missing convert "M" into a string, but after I changed to
print("Monthly payment: " + str(M))
I'm still getting the same error... Please help!
Needed a few changes:
# Loan Calculator
# Equation: M = L[i(1+i)^n]/[(1+i)(n)-1]
print("Loan Calculator")
L = float(input("Loan amount: "))
i = float(input("Interest rate: "))
# Remember: 5% ---> i=0.05
n = float(input("Number of payments: "))
M = L*(i*(1+i)**n)/((1+i)**(n)-1)
# M = Monthly payment
print("Monthly payment: " , M)
Using some arbitrary values:
Loan Calculator
Loan amount: 1000
Interest rate: 9
Number of payments: 100
('Monthly payment: ', 9000.0)