Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Specific statement every N iterations in Python

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading