I'm trying to understand how Python 3 handles the index variable value at the completion of a for loop. I'm a python newbie, with prior programming experience in C, so at this point, I "think" in C, and try to construct the equivalent code in Python.
Here's a toy example . . .
def tst(n): return n==6
for i in range(8,0,-1):
if tst(i): break
print(i)
for i in range(4,0,-1):
if tst(i): break
print(i)
After the first loop completes, the value of the variable i is 6, as expected.
But after the second loop completes, I expected (from my C experience) that the value of i would be 0 (i.e., the final value of i would fall one past the end of the range, unless there was a break), but the actual value is 1.
I want it to be 0.
As an alternative, I could code the second loop this way:
i=4
while i>0:
if tst(i): break
i-=1
print(i)
which works the way I want.
Is that the way to do it?
Update:
Thanks to all for explaining how Python interprets range expressions.
Using juanpa.arrivillaga's suggestion, I've settled for the following . . .
for i in range(4,0,-1):
if tst(i): break
else:
i=0
print(i)
elseonfor/whileloops: "I would not have the feature at all if I had to do it over."