I'm learning python on my own from a book and solving problems. In one problem, the user inputs amount of rain for each month in one year across a period of years. I need to find the average of rain in each year (sum(monthly rain)/numb_months, and also the average of rain in that period, e.g. in two years. In the following code, I can get the average for each year (I used 3 months only instead of 12 months to avoid tedious input now), but I don't know where I need to put an accumulator for total rain in that period and then average it. I appreciate your help.
number_of_months = 3
years_in_period = int(input("Please enter the number of years in the period. \n"))
for year in range(years_in_period):
yearly_rain = 0
print('Year', year+1)
print('−−−−−−−−−−−−−−−−−')
for month in range(number_of_months):
print('Month', month+1, end='')
monthly_rain = float(input("Please enter rainfall for this month: \n"))
yearly_rain += monthly_rain
average_yearly_rainfall = yearly_rain / number_of_months
print("Average yearly rainfall of year ", year+1, " is ", average_yearly_rainfall)
print("Year total rain is", yearly_rain)
print()
If I understood what you want (to calculate the absolute average of the rain amount during the period), this should do the trick:
number_of_months = 3
years_in_period = int(input("Please enter the number of years in the period. \n"))
total_rain = 0
for year in range(years_in_period):
yearly_rain = 0
print('Year', year+1)
print('−−−−−−−−−−−−−−−−−')
for month in range(number_of_months):
print('Month', month+1, end='')
monthly_rain = float(input("Please enter rainfall for this month: \n"))
yearly_rain += monthly_rain
total_rain += monthly_rain
average_yearly_rainfall = yearly_rain / number_of_months
print("Average yearly rainfall of year ", year+1, " is ", average_yearly_rainfall)
print("Year total rain is", yearly_rain)
print()
total_months = years_in_period * number_of_months
print("Absolute average of rain/month was", total_rain/total_months)
print("Absolute average of rain/year was", total_rain/years_in_period)
Related
I have a monthly budget code that shows the user if they are over/under the budget for a certain month. I am having trouble breaking the code up into def functions. here is what I have
print("""\
This program uses a for loop to monitor your budget.
The program will prompt you to enter your budget, and amount spent
for a certain month and calculate if your were under or over budget.
You will have the option of choosing how many months you would like to
monitor.\n""")
AmountSpent = 0
Budget = 0
numMonths = int(input("Enter the number of months you would like to monitor:"))
while numMonths<0:
print("\nNegative value detected!")
numMonths = int(input("Enter the number of months you would like to monitor"))
for month in range(1,numMonths+1):
print("\n=====================================")
AmountBudgeted = float(input(f"Enter amount budgeted for month {month}:"))
while AmountBudgeted<0:
print("Negative value detected!")
AmountBudgeted = float(input(f"Enter amount budgeted for month {month}:"))
AmountSpent = float(input(f"Enter amount spent for month {month}:"))
while AmountSpent<0:
print("Negative value detected!")
AmountSpent = float(input(f"Enter amount spent for month {month}:"))
if AmountSpent <= AmountBudgeted:
underB = AmountBudgeted - AmountSpent
print(f"Good Job! You are under budget by {underB}")
else:
overB = AmountSpent - AmountBudgeted
print(f"Oops! You're over budget by {overB}")
if month == "1":
print(f'your budget is {AmountBudgeted}.')
Can anyone help me break this code up into functions using "def" and other functions like "Describeprogram()" and "GetMonths()" ?
You could extract the user interaction like
def get_nb_months():
value = int(input("Enter the number of months you would like to monitor:"))
while value < 0:
print("Negative value detected!")
value = int(input("Enter the number of months you would like to monitor"))
return value
But then you notice that they're quite the same methods, so you can generalize:
def get_amount(msg, numeric_type):
value = numeric_type(input(msg))
while value < 0:
print("Negative value detected!")
value = numeric_type(input(msg))
return value
def summary(spent, budget):
diff = abs(budget - spent)
if spent <= budget:
print(f"Good Job! You are under budget by {diff}")
else:
print(f"Oops! You're over budget by {diff}")
if __name__ == "__main__":
numMonths = get_amount("Enter the number of months you would like to monitor:", int)
for month in range(1, numMonths + 1):
print("\n=====================================")
amount_budgeted = get_amount(f"Enter amount budgeted for month {month}:", float)
amount_spent = get_amount(f"Enter amount spent for month {month}:", float)
summary(amount_spent, amount_budgeted)
I have been working on this simple interest calculator and I was trying to make the for loop iterate until the amount inputted by the user is reached. But I am stuck at the range part, if I assign a range value like range(1 ,11) it will iterate it correctly and print the year in in contrast to the amount but I want the program to iterate until the year in which principal is greater than the amount is reached. My current code is bellow and the final product I want to reach is also attached bellow the current code. I'm new to python so please bare with me if I'm of track. Thanks in advance.
Current code:
principal = float(input("How much money to start? :"))
apr = float(input("What is the apr? :"))
amount = float(input("What is the amount you want to get to? :"))
def interestCalculator():
global principal
year = 1
for i in range(1, year + 1):
if principal < amount:
principal = principal + principal*apr
print("After year " + str (i)+" the account is at " + str(principal))
if principal > amount:
print("It would take" + str(year) + " years to reach your goal!")
else:
print("Can't calculate interest. Error: Amount is less than principal")
interestCalculator();
Final expected result:
Instead, you can use a while loop. What I mean here is you can simply:
principal = float(input("How much money to start? :"))
apr = float(input("What is the apr? :"))
amount = float(input("What is the amount you want to get to? :"))
def interestCalculator():
global principal
i = 1
if principal > amount:
print("Can't calculate interest. Error: Amount is less than principal")
while principal < amount:
principal = principal + principal*apr
print("After year " + str (i)+" the account is at " + str(principal))
if principal > amount:
print("It would take" + str(year) + " years to reach your goal!")
i += 1
interestCalculator()
A suggestion for a more pythonic solution
PRINCIPAL = float(input("How much money to start? :"))
APR = float(input("What is the apr? :"))
AMOUNT = float(input("What is the amount you want to get to? :"))
def interestCalculator(principal, apr, amount):
year = 0
yield year, principal
while principal < amount:
year += 1
principal += principal*apr
yield year, principal
for year, amount in interestCalculator(PRINCIPAL, APR, AMOUNT):
print(f"After year {year} the account is at {amount:.2f}")
if year == 0:
print("Can't calculate interest. Error: Amount is less than principal")
print(f"It would take {year} years to reach your goal!")
i am trying to get the percentage increase over a period of selected months .i cant seem to get a hold on how to make use of the current month value in calculating for the new month and summing all togther .
NOC = int(input('Please enter the number of chickens : '))
MONTHS = int(input('Please enter the number of months for the estimate : '))
FCE = NOC*10*MONTHS/100
if NOC == '' and MONTHS =='' :
print('please Enter a value for month and year')
else:
print('Your Result',FCE)
If you are looking for compound increase then you need to iterate over each month and use the last months value to increase
NOC = int(input('Please enter the number of chickens : '))
MONTHS = int(input('Please enter the number of months for the estimate : '))
for month in range(0, MONTHS):
NOC = NOC + (NOC*0.1)
print(NOC)
I wanted the result to show the total amount of money after adding interest every year but it only increases the year but not the amount. Why?
while True:
try:
investment = float(input('How much to invest : '))
interest = float(input('Interest rate : '))
break
except ValueError:
"Please enter a valid number"
for year in range(10):
money = investment + (investment * interest)
print("Total money in year {} : {}".format((year+1), money))
It sounds like you need to accrue the interest:
for year in range(10):
investment += (investment * interest)
print("Total money in year {} : {}".format((year + 1), investment))
Logical error. Your investment variable does not be assigned each round in the loop.
Suppose you have an investment plan where you invest a certain fixed amount at the beginning of every year. Compute the total value of the investment at the end of the last year. The inputs will be the amount to invest each year, the interest rate, and the number of years of the investment.
This program calculates the future value
of a constant yearly investment.
Enter the yearly investment: 200
Enter the annual interest rate: .06
Enter the number of years: 12
The value in 12 years is: 3576.427533818945
I've tried a few different things, like below, but it doesn't give me that 3576.42, it gives me only $400. Any ideas?
principal = eval(input("Enter the yearly investment: "))
apr = eval(input("Enter the annual interest rate: "))
years = eval(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print("The value in 12 years is: ", principal)
If it's a yearly investment, you should add it every year:
yearly = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
years = int(input("Enter the number of years: "))
total = 0
for i in range(years):
total += yearly
total *= 1 + apr
print("The value in 12 years is: ", total)
With your inputs, this outputs
('The value in 12 years is: ', 3576.427533818945)
Update: Responding to your questions from the comments, to clarify what's going on:
1) You can use int() for yearly and get the same answer, which is fine if you always invest a whole number of currency. Using a float works just as well but also allows the amount to be 199.99, for example.
2) += and *= are convenient shorthand: total += yearly means total = total + yearly. It's a little easier to type, but more important, it more clearly expresses the meaning. I read it like this
for i in range(years): # For each year
total += yearly # Grow the total by adding the yearly investment to it
total *= 1 + apr # Grow the total by multiplying it by (1 + apr)
The longer form just isn't as clear:
for i in range(years): # For each year
total = total + yearly # Add total and yearly and assign that to total
total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total
It can be done analytically:
"""
pmt = investment per period
r = interest rate per period
n = number of periods
v0 = initial value
"""
fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n
fv(200, 0.09, 10, 2000)
Similarly, if you are trying to figure out the amount you need to invest so you get to a certain number, you can do:
pmt = lambda fv, r, n, v0=0: (fv - v0*(1+r)**n) * r/((1.0+r)**n-1)
pmt(1000000, 0.09, 20, 0)
As suggested in the comments, you shouldn't use eval() here. (More info on eval can be found in the Python Docs). -- Instead, change your code to use float() or int() where applicable, as shown below.
Also, your print() statement printed out the parenthesis and comma, which I expect you didn't want. I cleaned it up in the code below, but if what you wanted is what you had feel free to put it back.
principal = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
# Note that years has to be int() because of range()
years = int(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print "The value in 12 years is: %f" % principal