Python while loop maybe need a break statement? - python

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

Related

A simple program from MIT OpenCourseWare. I wonder what's wrong, please?

The exercise program is from MIT OpenCourseWare. It asks me to calculate how many months can a down payment is fulfilled, with three portion:1. investment. 2. Part of the salary. 3. The salary gains a semi-year raise: this should only happen after the 6th, 12th, 18th month, and so on.
Here is my work:
current_saving = 0
annual_salary = int(input("Enter your annual salary:"))
portion_saved = float(
input("Enter the percent of your salary to save, as a decimal:"))
total_cost = int(input("Enter the cost of your dream home:"))
semi_annual_raise = float(input("Enter the semi- annual raise, as a decimal:"))
portion_down_payment = total_cost * 0.25
months = 0
while current_saving <= portion_down_payment:
if months % 6 !=1:
current_saving = current_saving * 0.04 /12 + annual_salary/12 * portion_saved + current_saving
months +=1
else:
annual_salary = annual_salary*(1+semi_annual_raise)
current_saving = current_saving * 0.04 /12 + annual_salary/12 * portion_saved + current_saving
months +=1
print(months)
This is my own run and sample test provided by an official document by MIT OpenCourseWare.
My own run
Please help me, thank you! I will get to interact as soon as possible.
Your issue is in the computation of every 6 month with the modulo. What you are doing is that you increase the salary everytime the month is in the form 6n + 1. Which means you increase the salary on month 1, 7, 13 etc. (as your index starts at zero, you are increasing the salary after the first month).
So you have a raise too early and the other ones too late.
Note: You have the same code in you if and else part, put it outside for easier to read and maintain code.
while current_saving <= portion_down_payment:
# Apply the raise every time the month is a multiple of 6 (as you start from 0, you need the +1 here)
if (months + 1) % 6 == 0:
annual_salary = annual_salary*(1+semi_annual_raise)
current_saving = current_saving * 0.04 /12 + annual_salary/12 * portion_saved + current_saving
months +=1

How to get a final report in years in for statement

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)

How do I add a counter to track the months and years in one while loop?

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

Nested Loops calculation output is incorrect, but program runs

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)

Nested loop for python

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

Categories

Resources