Reputation: 83
I recently ran into an issue where I was using a for loop somewhat similar to this:
for i in range(lineCount(fileToBeProcessed)):
print(i)
j = doSomeStuff() #returns number of lines in the file to skip
i = i+j
print(i)
print('next_loop')
For a value of j={2,3,1}
the output was:
1
3
next_loop
2
5
next_loop
.
.
My desired output:
1
3
next_loop
4
7
next_loop
.
.
Every time the next iteration started, the for loop counter i
reset to the original cycle. My question is, is there a way to force the for loop to skip the iterations based on the return value j
. I understand and was able to implement something similar with a while loop. However, I was curious as to how or why would Python not allow such manipulation?
Upvotes: 2
Views: 3704
Reputation: 21
I've edited the code hope it may help
z =0
for i in range(lineCount(fileToBeProcessed)):
if i <= z: #if i is a value that you don't want to be output, then skip loop to next one
continue
print(i)
j = doSomeStuff()
cnt += 1
z = i+j #use a different variable from i since i the iterator value will not be updated
print(z)
print('next_loop')
Upvotes: 0
Reputation: 82929
Assuming that fileToBeProcessed
is actually a file-like object, you can iterate directly over the file (i.e. over the lines in that file), or use enumerate(fileToBeProcessed)
if you need the line numbers, and call next
on that iterator to skip lines.
Like this (not tested):
iterator = enumerate(fileToBeProcessed) # or just iter = fileToBeProcessed
for i, line in iterator:
print(i)
j = doSomeStuff() #returns number of lines in the file to skip
for _ in range(j):
i, line = next(iterator) # advance iterator -> skip lines
print(i)
print('next_loop')
Upvotes: 1
Reputation: 476813
It allows manipulations. But a for
loop in Python works with a:
for <var> in <iterable>:
# ...
So Python does not attaches a special meaning to range(n)
as a for
loop: a range(n)
is an iterable that iterates from 0
to n
(exclusive). At the end of each iteration the next element of the iterable. It furthermore means that once you constructed a range(n)
, if you alter n
, it has no impact on the for
loop. This in contrast with for instance Java, where n
is evaluated each iteration again.
Therefore you can manipulate the variable, but after the end of the loop, it will be assigned the next value of the loop.
In order to manipulate the variable, you can use a while
loop:
i = 0 # initialization
while i < lineCount(fileToBeProcessed): # while loop
print(i)
j = doSomeStuff() #returns number of lines in the file to skip
i = i+j
print(i)
print('next_loop')
i += 1 # increment of the for loop is explicit here
Usually a while
loop is considered to be "less safe" since you have to do the increment yourself (for all code paths in the loop). Since it is something one tends to forget, it is easier to write an endless loop.
Upvotes: 3