Ranges and "for loops" within python?

Question:

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.

Asked By: apronedsamurai

||

Answers:

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.

Answered By: Moinuddin Quadri
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.