I'm learning python and I have a little snippet that is shown below:
for i in range(-10, 11, -6):
print(i)
This did not throw up an error nor give an output. Surprisingly I expected an error, since that stop value of 11
would never be hit. Any ideas why that is?
CodePudding user response:
Range represents an immutable sequence of numbers.
Here is a documentation of range
type.
In your case:
- start = -10
- stop = 11
- step = -6
For a negative step, the contents of the range are still determined by the formula r[i] = start step*i, but the constraints are i >= 0 and r[i] > stop.
A range object will be empty if r[0] does not meet the value constraint.
so let's try to generate range first element for your case
r[0] = -10 -6 * 0
r[0] = -10
but -10 is less than stop so algorithm stops here producing an empty range
>>> range(-10, 11, -6)
[]
so in your code range will be equivalent to this:
for i in []: # empty array, 0 iterations of loop, nothing printed to console
print(i)
and this code is perfectly valid python, "iterate over an empty range and finish" - that is why (1) nothing printed as range is empty, and (2) you got no error as code is valid