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.
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
.
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.
As mentioned in range(start, stop, step)
document:
if
step
is negative, the last element is the smalleststart + i * step
greater thanstop
.
Since you have step
of -2, you may use any value among 38 or 39 as stop
.