How am I able to get my program to display year 1 for the first 12 months and then year 2 for the next 12 months if the input value for years = 2?
Also I don't know where my calculation is going wrong. According to my desired output, the total rainfall output should be 37, but I am getting 39.
#the following are the values for input:
#year 1 month 1 THROUGH year 1 month 11 = 1
#year 1 month 12 THROUGH year 2 month 12 = 2
def main():
#desired year = 2
years = int(input("Enter the number of years you want the rainfall calculator to determine: "))
calcRainFall(years)
def calcRainFall(yearsF):
months = 12
grandTotal = 0.0
for years_rain in range(yearsF):
total= 0.0
for month in range(months):
print('Enter the number of inches of rainfall for year 1 month', month + 1, end='')
rain = int(input(': '))
total += rain
grandTotal += total
#This is not giving me the total I need. output should be 37.
#rainTotal = rain + grandTotal
#print("The total amount of inches of rainfall for 2 year(s), is", rainTotal)
print("The total amount of inches of rainfall for 2 year(s), is", grandTotal)
main()
Before the print statement, you don't need to add rain value again for rainTotal. This is because grandTotal accounts for the rain per year. And it is being added twice for two years already. So what you're doing is essentially adding the last value of rain twice (2 in this case)
Make your print statement this and remove rainTotal -
print("The total amount of inches of rainfall for 2 year(s), is", grandTotal)
I've shortened your code a little bit. Hopefully this is a complete and correct program:
def main():
years = int(input("Enter the number of years you want the rainfall calculator to determine: "))
calcRainFall(years)
def calcRainFall(yearsF):
months = 12 * yearsF # total number of months
grandTotal = 0.0 # inches of rain
for month in range(months):
# int(month / 12): rounds down to the nearest integer. Add 1 to start from year 1, not year 0.
# month % 12: finds the remainder when divided by 12. Add 1 to start from month 1, not month 0.
print('Enter the number of inches of rainfall for year', int(month / 12) + 1, 'month', month % 12 + 1, end='')
rain = int(input(': '))
grandTotal += rain
print("The total amount of inches of rainfall for", yearsF, "year(s), is", grandTotal)
main()
rainTotal = rain + grandTotal
is performing following: 2 + 37 because you have last rain input = 2 and already total or grandTotal is = 37 (total input for each year) so rainTotal = rain + grandTotal is not needed
Notes for your code:
As stated earlier, rainTotal is unneeded.
You can try:
print 'Enter the number of inches of rainfall for year %d month %d' % (years_rain, month), end='')
This will fill the first %d for the value for years_rain and the second %d with the value for month as your for loops run.
This trick can also be used on the final print line as shown below:
print("The total amount of inches of rainfall for %d year(s) % yearsF, is", grandTotal)
Related
I need the loop to follow the algorithm of the code below. Every loop should take the first day (2) and add the average (.3) to it.
startOrganism = 2
startOrganism = int(input("Starting number of organisms:"))
dailyInc = .3
dailyInc = float(input("Average daily increase (percent): "))
numberDaysMulti = 10
numberDaysMulti = int(input("Number of days to multiply: "))
for x in range(numberDaysMulti):
(Needs to be below)
Day 1 2
Day 2 2.6
Day 3 3.38
etc.
Ok, I've assumed that the user will input the percent daily increase as 0.3 as opposed to 30:
startOrganism = int(input("Starting number of organisms:"))
dailyInc = float(input("Average daily increase (percent): "))
numberDaysMulti = int(input("Number of days to multiply: "))
percDailyInc = 1 + dailyInc
for day in range(numberDaysMulti):
print(f'Day {day+1} {startOrganism:.2f}')
startOrganism *= percDailyInc
Sample Output:
Day 1 2.00
Day 2 2.60
Day 3 3.38
Day 4 4.39
Day 5 5.71
Day 6 7.43
Day 7 9.65
Day 8 12.55
Day 9 16.31
Day 10 21.21
This sort of computation can be handled mathematically, using the following formula:
organisms = starting_organisms * ((1.0 + growth_rate) ^ days)
Where the growth_rate is the percent increase per unit of time, in your case days. Then it becomes a matter of simply printing out the value for each day.
starting_organisms = int(input("Starting number of organisms:"))
growth_rate = float(input("Average daily increase in percent): ")) # 0.3 = 30%
period = int(input("Number of days to grow:"))
growth = [(starting_organisms * ((1.0 + growth_rate) ** day) for day in range(period)]
# The list 'growth' has all our values, now we just print them out:
for day, population in enumerate(growth):
print(f"Day {day} {population}")
(This uses a zero-index for the days. That is, 'day 0' will be your starting number. Indexing this way saves you off-by-one errors, but you can change the print statement to be {day + 1} to hide this data structuring from the user.)
There is an alternative method where you carry state in each loop, calculating the next day as you iterate. However, I'd recommend separating the concern of calculation and display - that instinct will serve you well going forward.
The growth = [... for day in range(period)] is a list comprehension, which works much like a one-line for-loop.
startOrganism = 0
startOrganism = int(input("Starting number of organisms:"))
dailyInc = 0
dailyInc = float(input("Average daily increase (percent): "))
dayApproximate = 0
numberDaysMulti = 0
numberDaysMulti = int(input("Number of days to multiply: "))
for x in range(numberDaysMulti):
startOrganism = dailyInc * startOrganism + startOrganism
print(startOrganism)
for p in range(running_weeks):
#Increase weeks in output
output_weeks = output_weeks + 1
#For backend to reset the total
function_total = function_total + income
#Real total shown in output
true_total = true_total + income
print("Week", output_weeks, "Income", income, "Total", true_total)
#For every 3000 in total the income increases and the functional total goes to 0
if math.floor(function_total / money_needed_for_increase) == 1:
income = income + increase_income
function_total = 0;
print("\nIncome increased by: ", increase_income, "\n")
#Every 52 weeks this message pops
if output_weeks % 52 == 0:
print("\nYear ", output_weeks / 52, "Done Results: Income:", income, "Total", true_total,"\n")
With this for statement I'm able to see what happens each week and how much my income will increase and when the year is over. But, I would like to add something so that when the for statement is over, it shows a result of how much I made each year.
Ex:
Year 1.0 Income: 10,000 Total: 100,000
Year 2.0 Income: 11,000 Total: 500,000
and so on
If I understand correctly, you want to split running_weeks into full years. You can simple use a for loop for that. Here's the example:
years = []
for i in range(0, len(running_weeks), 52):
years.append(running_weeks[i : i + 52])
It will split running_weeks into few pieces of size 52. Then you can easily calculate all data about each year.
Try tracking years as a list of sublists, then iterate through the years at the end. So before your code, add the years list:
years = []
for p in range(running_weeks):
And as you total each year, append to years:
#Every 52 weeks this message pops
if output_weeks % 52 == 0:
print("\nYear ", output_weeks / 52, "Done Results: Income:", income, "Total", true_total,"\n")
years.append[[income, true_total]]
Then at the end, iterate through the years. Indexes start at 0 and you want year 0 to be treated as 1, so use i+1:
for i in range(len(years)):
year_income, year_total = years[i]
print('Year', i+1, 'Income:', year_income, 'Total:', year_total)
so I am trying to create a program and I have the program complete for the most part but I am having some trouble with counters.
-I need to add a counter for months and years that track how long it will take to become a millionaire.
-I have the months counter correct, but I am having trouble trying to figure out the years counter.
Here is my code so far:
balance = float(input("Enter initial amount: "))
monthlyContribution = float(input("Enter monthly contribution: "))
interestRate = float(input("Enter annual interest rate: "))
month = 0
year = 0
while balance < 1000000 :
month = month + 1
year = year + 1
interest = interestRate/100
balance = balance + monthlyContribution + (balance + monthlyContribution) * interest/12
print(f'Current Balance: ${balance:,.2f}', (f'after {month} months'), (f' or {year} years'))
print(f'Congratulations, you will be a millionaire in {month} months: ${balance:,.2f}')
After discussion here is final result:
balance = float(input("Enter initial amount: "))
monthlyContribution = float(input("Enter monthly contribution: "))
interestRate = float(input("Enter annual interest rate: "))
month = 0
interest = interestRate/100
while balance < 1000000 :
month = month + 1
balance += monthlyContribution + (balance + monthlyContribution) * interest/12
if not month % 12:
year = month//12
rem = month % 12
print(f'Current Balance: ${balance:,.2f} after {month} or {year} years' +
f'and {rem} months')
year = month//12
rem = month % 12
print(f'\nCongratulations, you will be a millionaire in {month} months' +
f' or {year} years and {rem} months' +
f'\nCurrent Balance: ${balance:,.2f}')
#vash_the_stampede's answer works. If you wanted to have a whole number of years, you could also increment the counter for year when month is a multiple of 12.
if month >= 12 and month % 12 == 0:
year += 1
I need for this code to stop calculating the increase of the salary after year 20. I tried adding another while loop but that caused an infinite loop to occur. Any help would be greatly appreciated!!
RATE = 2.0
INITIAL_SALARY = 37238.00
salary = INITIAL_SALARY
year = 1
print("Murdock County")
print("Teacher Salary Schedule")
print()
print("Year Salary")
print("---- ------")
while year < 31 :
print("%4d %15.2f" % (year, salary))
increase = salary * RATE / 100
salary = salary + increase
year = year + 1
You probably typed 31 instead of 21, so
while year < 21 :
# your code
Or you could probably mean that after 21 the salary is no longer increased, so:
while year < 31 :
print("%4d %15.2f" % (year, salary))
if year < 21:
increase = salary * RATE / 100
salary += increase
year += 1
You can use a for loop alternatively because you know the number of times the loop will be executed, and make some improvements as probably removing the variable INITIAL_SALARY, using a string enclosed in tripe double or single quotation marks to avoid using too many print statements:
RATE = 2.0
salary = 37238.00
print("""Murdock County
Teacher Salary Schedule
Year Salary
---- ------""")
for year in range(1, 31):
print("%4d %15.2f" % (year, salary))
if year < 21:
increase = salary * RATE / 100
salary += increase
year += 1
while year < 31 :
print("%4d %15.2f" % (year, salary))
if year < 21:
increase = salary * RATE / 100
salary = salary + increase
year = year + 1
I have problem with a nested loop problem. In a year, I want my loop to add up every number from the month of the year. When the year is over instead of adding the numbers from last year and adding it to the new year, i want it to begin again at 0.
Finally, it should show me the total of each year and give me an average of all the years.
Here is my sample if anyone could help me finish it:
total_rain = 0
month = 12
y = 0
rain = 0
month_rain = 0
years = int(input("How many years: "))
for y in range(years):
y += 1
print()
print("In the year", y,"There will be:")
for m in range(month):
rain = float(input('How many inch of rainfall have fallen: '))
total_rain += rain
print(month_rain)
main()
Every time a loop ends, it adds the number from the previous year. I want the new loop to start at 0 again and add up the numbers.
for y in range(years):
y += 1
for m in range(month):
rain = float(input('How many inch of rainfall have fallen: '))
total_rain += rain
print("In the year", y,"There will be:", total_rain," inches of rain")
#reset variable
total_rain = 0
First of all, I corrected the indentation of "total_rain += rain" because you had it nested outside of the 2nd for loop, therefore it wouldn't actually add the rain you input each time.
Then all I did was set the total rain to 0 to reset it.
It works like a charm and is very similar to your own code.
total_rain = []
months = 12
years = int(input("How many years: "))
for y in range(1, years+1):
print("In the year", y,"There will be:")
annual_rain = []
for m in range(1,13):
rain = float(input('How many inch of rainfall have fallen in month %s: ' %m))
annual_rain.append(rain)
total_rain.append(annual_rain)
for y,year in enumerate(total_rain, 1):
print("Total rain in year %s: %s. Average monthly rain: %s" %(y, sum(year), sum(year)/len(year)))
total_rain = 0
month = 12
rain = 0
years = int(input("How many years: "))
for y in range(years):
month_rain = 0
print()
print("In the year", y,"There will be:")
for m in range(month):
rain = float(input('How many inch of rainfall have fallen: '))
month_rain += rain
total_rain += month_rain
print("year %s: %s" % (y, month_rain) )
print("total rain: %s" % (total_rain/years))