@ Padraic Cunningham Let me know if you want me to delete the question.
I am new to python. I want to skip some iterator values based on some condition. This is easy in C but in python I am having a hard time.
So please help me in understanding why the code here loops 100 times instead of 10.
for i in range(100):
print i
i = i +10
edit: I understand there is option to change step size of for loop. But I am interested in dynamically changing the iterator variable, like we can do in C. Okay, i get it, for loop is different in python than in C. Easy way to do is use the while loop, I did that in my code and it worked. Thank you community!
The for loop is walking through the iterable range(100)
.
Modifying the current value does not affect what appears next in the iterable (and indeed, you could have any iterable; the next value might not be a number!).
Option 1 use a while loop:
i = 0
while i < 100:
i += 4
Option 2, use the built in step size argument of range:
for i in range(0,100,10):
pass
This example may make it clearer why your method doesn't make much sense:
for i in [1,2,3,4,5,'cat','fish']:
i = i + i
print i
This is entirely valid python code (string addition is defined); modifying the iterable would require something unintuitive.
See here for more information on how iterables work, and how to modify them dynamically
To do this use a while loop. Changing the iterator in a for loop will not change the amount if times it iterates Instead you can do
i=0
while i < 100:
print i
i = i +10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With