1

I want to iterate through different dates, for instance from 20/08/2015 to 21/09/2016, but I want to be able to run through all the days even if the year is the same. For instance 20/08/2015 to 25/09/2015.

Now if I write this in C, I could just use a for loop and make it so it runs if value of startYear <= value of endYear, but from all the examples I see online the for loop runs with the range function, which means if I give it the same start and end values it will simply not run.

For example:

startYear=int(raw_input("Starting year (yyyy):"));
endYear=int(raw_input("Ending year (yyyy):")); 
for year in range(startYear,endYear,1):

As the input comes from the user I have no control over it. So if startYear and endYear are both 2015 I can't make it iterate even once. Note that I can't "cheat" by changing the values of startYear and endYear as I am using the variable year for calculations later.

I would love to know:

  1. Is there a way to run a for loop in Python that checks for lower or equal?
  2. What is the best way to go about writing this simple iteration?

Thanks

SteveR
  • 13
  • 1
  • 4

1 Answers1

0
  1. You can use endYear + 1 when calling range. Also note that passing 1 to the step argument is redundant.

    for year in range(startYear, endYear + 1):
    
  2. You can use dates object instead in order to create a dates range, like in this SO answer.

Community
  • 1
  • 1
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • just to be clear if i run: for year in range(startYear ,endYear+1) year would only have a value of startYear , run once then the for loop is finished am i correct ? – SteveR Aug 07 '16 at 08:13
  • Thanks , i didn't think about it like that this is exactly what i wanted sometimes the easy things just do not appear in front of you im sorry i cant affect the Answers' score but i up voted it thanks – SteveR Aug 07 '16 at 12:42