Search code examples
pythonaccumulator

How do I use an accumulator with a for loop range in Python?


I am trying to use an accumulator in Python but I cannot get it to work. I want the population to start out at 2 and increase by the percentIncrease input but it is not coming out correctly. What am I doing wrong? I know it is how I am accumulating it but every attempt I have tried has failed.

#Get the starting number of organisms
startingNum = int(input('Enter the starting number of organisms:'))

#Get the average daily increase
percentIncrease = float(input('Enter the percentage of average daily increase of organisms:'))

#Get the number of days to multiply
number_of_Days = int(input('Enter the number of days to multiply:'))

population = 0
cumPopulation = 0

for number_of_Days in range(1,number_of_Days + 1):
    population = startingNum
    cumPopulation += population *(1+percentIncrease)
    print(number_of_Days,'\t',cumPopulation)


#So inputs of 2, .3, and 10 should become:
1   2
2   2.6
3   3.38
4   4.394
5   5.7122
6   7.42586
7   9.653619
8   12.5497
9   16.31462
10  21.209

Solution

  • Not sure do you need to print day 1 as the startingNum or day 1 as startingNum * (1+ percentIncrease).

    This is what you want:

    #Get the starting number of organisms
    startingNum = int(input('Enter the starting number of organisms:'))
    
    #Get the average daily increase
    percentIncrease = float(input('Enter the percentage of average daily increase of organisms:'))
    
    #Get the number of days to multiply
    number_of_Days = int(input('Enter the number of days to multiply:'))
    
    printFormat = "Day {}\t Population:{}" 
    cumPopulation = startingNum
    
    print(printFormat.format(1,cumPopulation))
    
    for number_of_Days in range(number_of_Days):
        cumPopulation *=(1+percentIncrease) # This equals to cumPopulation = cumPopulation * (1 + percentIncrease)
        print(printFormat.format(number_of_Days+2,cumPopulation))
    

    Output:

    Enter the starting number of organisms:100
    Enter the percentage of average daily increase of organisms:0.2
    Enter the number of days to multiply:10
    Day 1    Population:100
    Day 2    Population:120.0
    Day 3    Population:144.0
    Day 4    Population:172.8
    Day 5    Population:207.36
    Day 6    Population:248.832
    Day 7    Population:298.5984
    Day 8    Population:358.31808
    Day 9    Population:429.981696
    Day 10   Population:515.9780352
    Day 11   Population:619.17364224