for i in range (0, 81): output = send command while True: last_byte = last_byte - offset if last_byte > offset: output = send command i+ else: output = send command i+ break
I want to increase the iterator every time the send command is executed. Right now it only increases by one when the for loop is executed. Please advise
for i in range(0,10): print(i) i +=2 print("increased i", i)
I ran this code and it produced out from 0 to 9. I was expecting it would increase the iterator by 2.
A for loop doesn't increment anything. Your code used in the for statement does. It's entirely up to you how/if/where/when you want to modify i or any other variable for that matter.
To iterate through an iterable in steps, using for loop, you can use range() function. range() function allows to increment the “loop index” in required amount of steps.
Save a copy of the iterator as a named object. Then you can skip ahead if you want to.
>>> myiter = iter(range(0, 10)) >>> for i in myiter: print(i) next(myiter, None) ... 0 2 4 6 8
You can't do that inside a for
loop. Because every time that the loop gets restarted it reassign the variable i
(even after you change it inside the loop) and every time you just increase the reassigned variable. If you want to do such thing you better to use a while
loop and increase the throwaway variable manually.
>>> i=0 >>> while i< 10 : ... print(i) ... i +=2 ... print("increased i", i) ... 0 ('increased i', 2) 2 ('increased i', 4) 4 ('increased i', 6) 6 ('increased i', 8) 8 ('increased i', 10)
Beside that, if you want to increase the variable on a period rather than based some particular condition, you can use a proper slicers to slice the iterable in which you're looping over.
For instance if you have an iterator you can use itertools.islice()
if you have a list you can simply use steps while indexing (my_list[start:end:step]
).
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