1

I have used a for loop.

for i in range (100, 40, -2):
    print ("T-minus:")
    print (i)

The code is executed with the final output being T-minus: 42

I understand that the loop has been executed up to, but not including, the value 40. I was curious as to how I would go about ensuring that both both "poles" of a range are specified/included? Would I need to artifically "low-ball" my range? So for example, if I decremental factor is -2, and I want the range to stop at 40, would I then have to state 38, making my code the following:

for i in range (100, 38, -2):
    print ("T-minus:")
        print (i)

?

My question specifically pertains to loops.

apronedsamurai
  • 73
  • 1
  • 11
  • 1
    Possible duplicate of [How should I handle inclusive ranges in Python?](http://stackoverflow.com/questions/29596045/how-should-i-handle-inclusive-ranges-in-python) – ayhan Dec 11 '16 at 19:21
  • No, my question pertains to loops specifically. – apronedsamurai Dec 11 '16 at 19:24

1 Answers1

1

As mentioned in range(start, stop, step) document:

if step is negative, the last element is the smallest start + i * step greater than stop.

Since you have step of -2, you may use any value among 38 or 39 as stop.

Moinuddin Quadri
  • 43,657
  • 11
  • 92
  • 117