Compute future tuition - python

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:"))

Related

Calculate 20 minute average & best 20 minute average

I'm trying to learn Python, with a project where I'm reading data from a bike power meter. Right now I'm just calculating the average power from start to finish, by adding each power reading to a total sum variable, and dividing it with the number of readings.
I'd like to calculate the average power for 20 minutes, and if possible, keep calculating the 20 minute average each 30 seconds after the first 20 minutes, comparing to the previous value and storing it if it's higher than the last, so in the end I could have the higher 20 minute average power that I held during a one hour workout, no matter where it happened in that hour, for example.
Data from the power meter is event based, as far as I can tell it's not a regular intervals, but definitely once a second or faster.
This is the base of my code so far:
def average_power(power, count):
global PM1_sumwatt
global PM1_avgwatt
PM1_sumwatt = PM1_sumwatt + power
PM1_avgwatt = PM1_sumwatt / count
PM1_avgLog = open(PM1_avgFile, 'w')
PM1_avgLog.write("<div id=\"pwr\"> %d W</div>" % (PM1_avgwatt))
PM1_avgLog.close()
def power_data(eventCount, pedalDiff, pedalPowerRatio, cadence, accumPower, instantPower):
global PM1_avgcount
if WCORRECT1: calibpower = instantPower+(CF1w)
else: calibpower = instantPower*(CF1x)
power_meter.update(int(calibpower))
PM1_avgcount = PM1_avgcount + 1
average_power(int(calibpower), PM1_avgcount)
power = BicyclePower(readnode, network, callbacks = {'onDevicePaired': device_found,
'onPowerData': power_data})
# Starting PM readings
power.open(ChannelID(PM1, 11, 0))
Not quite sure how to tackle this! Any help or pointer is much appreciated!
if you are reading data in real time, I assume you are reading the data in a while loop:
sum = 0
number_of_readings = 0
while True: # forever
new_value = input() # here I read from the console input
sum += new_value
number_of_readings += 1
average = sum/number_of_readings
print(average)
Here I type a number in the console and press enter to simulate your bike power meter.
>>> 1
1.0
>>> 3
2.0
>>> 4
2.6666666666666665
>>> 2
2.5
Now, if you wants to make a moving average, you must store the readings that you wants to average. This is because you want to remove them later, when they will be too old. A list is perfect for that:
Here is a solution averaging the last n readings:
n = 2
Last_n_readings = []
while True: # forever
# add a new reading
new_value = int(input()) # here I read from the console input
Last_n_readings.append(new_value)
# discard an old one (except when we do not have enough readings yet)
if len(Last_n_readings) > n:
Last_n_readings.pop(0)
# print the average of all the readings still in the list
print(sum(Last_n_readings) / len(Last_n_readings))
Which gives:
>>> 1
1.0
>>> 3
2.0
>>> 4
3.5
>>> 2
3.0
Note that lists are not very efficient when removing elements near the start, so there are more effective ways to do this (circular buffers), but I try to keep it simple ;)
You could use this by guessing how many readings/seconds you have and choose n so you average over 20 minutes.
If you want to truly average all the result which are less than 20 minutes ago, you need to not only record the readings but also the times when you red them, so you can remove the old readings wen they get more than 20 minutes old. If this is what you need, tell me and I will expand my answer with an example.
You can use pandas dataframe to store the power output for each instance.
Considering that you receive a value each 30 second, you can store them all in data frame.
Then calculate a 40 data point moving average using rolling function in python.
Take the max value you get after the rolling function, this would be your final result.
refer this for doc : https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html

Calculating Total from interest, principle and years using FOR LOOP

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)

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()

Define a function or loop, which restarts if given integer-parameter is less than X, or refuses to accept value less than 3

I'm writing a simple program where a person can go on a trip, but the trip has to last 3 days minimum. The whole program has more parts which all work well, and the whole program works, but now I want to enhance it and set the minimal parameter value of function hotel_cost(days) to 3
In it's most basic form, my function is:
def hotel_cost(days):
# hotel costs 140$ per day
return 140 * int(days)
And the above obviously works, but I want to change it so that it does not accept less than 3.
I'm experimenting with while and a boolean but it gives me None, and I've also faced accidental infinite recursion. Sorry if this question is too basic, it's my first one. I tried searching but to no avail.
Your can condense asking the user for the number of days, and giving them there price in in one function.
def ask_num_hotel_days():
i = int(input("Enter nuber of days: "))
while(i < 3):
print(str(i) + " is not a valid number of days")
i = int(input("Enter nuber of days: "))
return 140 * i
From my understanding of the question, you can do this:
def hotel_cost(days):
if int(days) >= 3:
return 140 * int(days)
else:
return False
And then you can do:
while not hotel_cost(days):
print("How many days are you staying?")
days = input()
Once it gets out of the while, the days amount will be valid, as well as the cost.
EDIT :
I wrote the code inside the while loop, to be more clear about what I suggested.
I hope it helps.
Cheers.

Silly Python Beginner

Having some trouble grasping why this "quick math" formula I was taught in high school does not seem to work correctly.
The premise is to take your hourly salary, double it and add three Zeros, the result will roughly equate to your yearly salary if you work full time 50 weeks out of the year.
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = raw_input("How much money do you earn per hour?")
# Math Work
mult = money * 2
result = mult + str(000)
# Answer
print "you make roughly $%r per year, Working full-time for 50 weeks out of the year" % result
Result:
my result looks something like this: "you make roughly $10100 per year, working full-time for 50 weeks out of the year"
I must be making a mistake in my expression...Simply put, I just do not know
You got all the types wrong.
raw_input acquires a string, so money is acquired as such. Thus, when you do mult=money*2 you are not doubling a number, but a string; writing money*2 thus has the effect of creating a string that is the concatenation of two copies of the string you provided. If you enter 10, mult will be '1010'.
Also, in str(000) 000 is an integer, so it's actually a plain 0; str(000) thus results in '0', which is concatenated to your doubled-string. 1010 concatenated with '0' => 10100.
What you actually want is
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
mult = money * 2
result = str(mult) + "000"
By the way, adding zeroes and the like is fine for humans, but since we are dealing with a computer you can just multiply by 2000:
result = 2000*int(raw_input("How much money do you earn per hour?"))
You're trying to do math with a string. Convert it into an integer first:
money = int(raw_input("How much money do you earn per hour?"))
and multiply instead of trying to add a string to the end
result = money * 2000
Though if you really wanted to, you could convert the integer back to a string to add 3 zeros to the end:
mult = money * 2
strmult = str(mult)
result = strmult + '000'
The raw_input() function returns a string.
When you multiply money by a number, instead of multiplying the integer value, you are multiplying the string value. This results in the variable's new value being a multiple of the string, or the string repeated multiple times. I would suggest using the money=int(money) function on money to turn it into an integer, or better yet money=float(money) to get a floating-point number.
try this
money=int(input('how much you make an hour'))
final_yearly=money*2000
print(final_yearly)
You do realize the following would give you the desired answer, right?
#Math Work
mult = money * 2000
First, money is a string, when you read user input. So when the user inputs 10, you get '10'.
So when you do money*2, you don't get the expected 20. Rather, you get '10'*2, which is '10' concatenated twice, i/e/ '1010'.
Next, 000 is an int that evaluates to 0, the str of which is '0'. What you wanted to add is '000'
I would go about your task this way:
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
mult = money * 2
result = str(mult) + "000"
Alternatively, you could do this as well:
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = int(raw_input("How much money do you earn per hour?"))
# Math Work
result = money*2000 # because adding three 0s is the same as multiplying by 1000
# Preface
print '---> Want to know your yearly salary? <---'.upper()
# Question
money = raw_input("How much money do you earn per hour?")
# Math Work
result = str(int(money)*2) + '000'
# Answer
print "you make roughly $%r per year, Working full-time for 50 weeks out of the year" % result

Categories

Resources