Home > Blockchain >  Specific statement every N iterations in Python
Specific statement every N iterations in Python

Time:01-07

I want to create a loop that for every 12 months, the 'year' variable should increment by 1 until reach the limit. I couldn't make it on my own. This is what I tried (in this case, the ending should be in 2013):

years=[]
begin= 2010
for i in range(0,40):
    year= begin
    if ((i % 12 == 0) and (i != 0)):       
        year =1
        years.append(year)
    else:
        years.append(year)
years

The only result that I get is: [2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2010, 2011, 2010, 2010...]

Help is much appreciated!

CodePudding user response:

This is what you can do:

I assume that the range is believed to be the number of months here.

years = [] # store the years from begin
begin = 2010
count_years = -1
for i in range(0,40,12):  # each 12 months a year - step 12
    count_years  =1  # add one year after each increment
    end  = begin   count_years  # find the end year until last increment
    years.append(end) # append to the list.

print(years)

Printing the years will give you:

[2010, 2011, 2012, 2013]

I hope this is what you need.

  •  Tags:  
  • Related