Calculating Total from interest, principle and years using FOR LOOP - python

I am trying to create a program that asks the user their principal, interest rate, and total amount of years. I want my program to show them the amount of total return they would expect for each year. I want it to start at year 1. When I run my script, it only shows one year's worth total interest. Here is what I have so far.
#Declare the necessary variables.
princ = 0
interest = 0.0
totYears = 0
year = 1
#Get the amont of principal invested.
print("Enter the principal amount.")
princ = int(input())
#Get the interest rate being applied.
print("Enter the interest rate.")
interest = float(input())
#Get the total amount of years principal is invested.
print ("Enter the total number of years you're investing this amonut.")
totYears = int(input())
for years in range(1, totYears):
total=year*interest*princ
years += 1
print (total)
Thank you any help is appreciated.

There are problems here:
for years in range(1, totYears):
total=year*interest*princ
years += 1
print (total)
You change years within the loop. Don't. The for statement takes care of that for you. Your interference makes years change by 2 each time through the loop.
Every time through the loop, you throw away the previous year's interest and compute a new one. Your print statement is outside the loop, so you print only the final value of total.
Your loop index is years, but you've computed on the variable year, which is always 1. A programming technique I picked up many years ago is never to use a plural variable name.
Perhaps you need this:
for years in range(1, totYears):
total = years * interest * princ
print (total)

Related

Compute future tuition

I have a problem I need to calculate future tuition depending on the input that the user puts. So for example the tuition is 5,000 per year and increases by 7% every year. If a user inputs 6 the program should print the total cost of tuition for years six, seven, eight and nine. So far I have this.
year = 1
n = int(input())
tuition = 5000
for i in range (n,n + 3):
tuition = tuition * 1.07
year = year + 1
print (tuition)
Regardless of what the user inputs, your for loop will run through 3 iterations.
It looks like you're trying to add a 7% increase (compound) every year for 3 years.
You don't need a loop for that.
e.g.,
tuition = 5_000
years = 3
increase = 1.07
print(tuition * increase ** years)
Output:
6125.215
A few hints
The problem with your program is that you are looping using a for loop but you are not using the value i within your for loop. You should use it. Additionally think about how many times your print() statement is executed. Only once, but you need it for every year so think about moving it into the for loop as well.
One other thing: input() takes a string as a parameter so you can provide some description of what a user is supposed to enter. You should use this as well to make your program usable.
n = int(input("Please enter a start year:"))

Calculating house down payment [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 5 years ago.
Improve this question
Using Python 3.6
You have graduated from MIT and now have a great job! You move to the San Francisco Bay Area and decide that you want to start saving to buy a house. As housing prices are very high in the Bay Area, you realize you are going to have to save for several years before you can afford to make the down payment on a house. In Part A, we are going to determine how long it will take you to save enough money to make the down payment given the following assumptions:
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
So far, I have this basic code:
annual_salary = float(input("Type annual salary here : "))
portion_saved = float(input("Type the portion you want to save (as a decimal) : "))
total_cost = float(input("Type the cost of your dream house here : "))
monthly_salary = (annual_salary / 12.0)
portion_down_payment = 0.25 * total_cost
current_savings = 0 + ???
returns = (current_savings * 0.4) / 12
overall_savings = returns + (portion_saved * monthly_salary)
months = ???`
My problem is that I have no idea how to calculate the months.
I do not know if I need to create an IF statement, a loop, or none of them at all.
The months are the value it will take to reach your necessary amount.
For example, you want to loop up until you have enough for the down payment.
months = 0
# Want to exit the loop when there is enough savings for a down payment
while current_savings < portion_down_payment:
current_savings += current_savings * (0.4 / 12) # Monthly interest
current_savings += portion_saved # Monthly savings
months += 1
print("It will take {} months to save!".format(months))
This can be solved analytically.
down_payment_rate = 0.25
saving_rate = 0.10
r = 0.04 #investment rate
target = total_cost * down_payment_rate
M = annual_salary/12*saving_rate/12 #Monthly savings
The question is to solve the following:
target = M*(1+r) + M*(1+r)^2 + M*(1+r)^3 ... M*(1+r)^N
The above is a geometric series, where N is the number of months to reach the target. This can be expressed succinctly as:
let g = 1+r:
target = M * (1-g^N)/(1-g)
You already know g, target, M, the only thing to solve for is N. you can find the result using algebra. Ie: N = log(1-target*(1-g)/M)/log(g)
You just need a while loop:
Initialize the months variable to 0 and ensure that the savings don't exceed and is less than or equal to the down payment. Also ensure that you set Current Saving to 0 initially
Current_Saving=0
rate=0.04/12
monthly_savings = monthly_salary*0.1
i=0
while (Current_Saving <= down_payment):
Current_Saving = Current_Saving+(monthly_savings)*rate + monthly_savings
i=i+1
print(i)
I will give the total number of months. Monthly salary can be obtained by dividing the annual salary by 12.

How can I find out the number of outputs in a loop?

I am a beginner at python and I'm struggling with one of my (simple) college assignments. I have been given the following instructions:
A bank is offering a savings account where a yearly fee is charged. Write
a program that lets the user enter
An initial investment.
The yearly interest rate in percent.
The yearly fee.
the program should then calculate the time it takes
for the investment to double. The interest is added on once per year.
An example run of the program:
Enter the investment: 1000
Enter the interest rate: 10
Enter the fee: 10
The investment doubles after 7 years.
I have formulated the following code but am receiving an error message with regards to t. I would really appreciate if I could get some help, thanks!:
t=0
p=float(input("Enter the investment:"))
a=float(input("Enter the interest rate:"))
m=float(input("Enter the fee:"))
i=(float(a/100))
f=p
while f<=(2*p):
f=(float(f*((1+i)**t)-m)
t=t+1
print("The investment doubles after",t,"years")
I tried to write this in a way that was very easy to follow and understand. I edited it with comments to explain what is happening line by line. I would recommend using more descriptive variables. t/p/a/m/f may make a lot of sense to you, but going back to this program 6 months from now, you may have issues trying to understand what you were trying to accomplish. NOTE You should use input instead of raw_input in my example if using Python 3+. I use 2.7 so I use raw_input.
#first we define our main function
def main():
#investment is a variable equal to user input. it is converted to a float so that the user may enter numbers with decimal places for cents
investment = float(raw_input("Starting Investment: "))
#interest is the variable for interest rate. it is entered as a percentage so 5.5 would equate to 5.5%
interest = float(raw_input("Interest Rate as %, ex: 5.5 "))
#annual_fee is a variable that will hold the value for the annual fee.
annual_fee = float(raw_input("Annual Fee: "))
#years is a variable that we will use with a while loop, adding 1 to each year (but we wait until within the loop to do this)
years = 1
#we use a while loop as opposed to a for loop because we do not know how many times we will have to iterate through this loop to achieve a result. while true is always true, so this segment is going to run without conditions
while True:
#this is a variable that holds the value of our total money per year, this is equal to the initial investment + investment * interest percentage - our annual fee per year
#I actually had to try a few different things to get this to work, a regular expression may have been more suited to achieve an interest % that would be easier to work with. do some research on regular expressions in python as you will sooner or later need it.
total_per_year = investment + (years * (investment * (interest / 100))) - (annual_fee * years)
#now we start adding 1 to our years variable, since this is a while loop, this will recalculate the value of total_per_year variable
years += 1
#the conditional statement for when our total_per_year becomes equal to double our initial investment
if total_per_year >= 2 * investment:
#print years value (at time condition is met, so it will be 5 if it takes 5 years) and the string ' Years to Double Investment'
print years,' Years to Double Investment'
#prints 'You will have $' string and then the value our variable total_per_year
print 'You will have $', total_per_year
#this will break our while loop so that it does not run endlessly
break
#here is error handling for if the fee is larger than investment + interest
if (years * annual_fee) >= (years * (investment * (interest / 100))):
print('Annual Fee Exceeds Interest - Losing Money')
break
#initial call of our main function/begins loop
main()

What should I use for my program to calculate the savings for more than one year?

initial = int(input ("What is your initial balance?:"))
interest = float(input ("What is the annual percentage for interest as a decimal?:"))
yearsinvested = input ("How many years is the money being invested for?:")
nextyear=initial*(1+interest)
print ("After year 1:",nextyear ,)
What do I use to make it calculate+print for the amount of years inputted by the user?
Is it a while/for loop? if statement?
I've had a mental block >.<
Is it a while/for loop? if statement?
Yes, it's a while or for loop, based on your personal taste. Personally, I'd go for a for loop! ;)
Here is a for loop. Notice that yearsinvested should be an int. You can fill in your other bits
yearsinvested = int(input("How many years is the money being invested for?:"))
for y in range(1, yearsinvested + 1):
# do some stuff here
print ("After year {}: {}".format(y, nextyear))

python string formatting error in a definite loop

def main():
#Get amount of principal, apr, and # of years from user
princ = eval(input("Please enter the amount of principal in dollars "))
apr = eval(input("Please enter the annual interest rate percentage "))
years = eval(input("Please enter the number of years to maturity "))
#Convert apr to a decimal
decapr = apr / 100
#Use definite loop to calculate future value
for i in range(years):
princ = princ * (1 + decapr)
print('{0:5d} {0:5d}'.format(years, princ))
I'm trying to print the years and the principal value in a table, but when I print all that comes out is two columns of 10.
So you have several problems. The first problem is a display issue.
Your output statement print('{0:5d} {0:5d}'.format(years, princ)) has several issues.
printing years instead of i, so it's always the same value instead of incrementing
the 0 in the format statement{0:5d} means the 0'th element out of the following values, so you're actually printing years twice, the second one should be 1 instead of 0
you're using d to print what should be a floating point value, d is for printing integers, you should be using something along the lines of {1:.2f} which means "print this number with 2 decimal places
Once you've corrected those you'll still see incorrect answers because of a more subtle problem. You're performing division with integer values rather than floating point numbers, this means that any decimal remainders are truncated, so apr / 100 will evaluate to 0 for any reasonable apr.
You can fix this problem by correcting your input. (As a side note, running eval on user input is usually an incredibly dangerous idea, since it will execute any code that is entered.) Instead of eval, use float and int to specify what types of values the input should be converted to.
The following is corrected code which implements the above fixes.
#Get amount of principal, apr, and # of years from user
princ = float(input("Please enter the amount of principal in dollars "))
apr = float(input("Please enter the annual interest rate percentage "))
years = int(input("Please enter the number of years to maturity "))
#Convert apr to a decimal
decapr = apr / 100
#Use definite loop to calculate future value
for i in range(years):
princ = princ * (1 + decapr)
print('{0} {1:.2f}'.format(i, princ))

Categories

Resources