How is this working and for loop increment doesn’t work?
for i in range(0,10):
if i == 3:
i = i + 1
continue
print(i)
for the code,
for i in range(0,10):
if i == 3:
i = i + 1
continue
print(i)
the output is going to be,
0
1
2
4
5
6
7
8
9
Breaking down the code,
for i in range(0, 10)
for loop runs for i=0 to i=9, each time initializing i with the value 0 to 9.
if i == 3:
i = i + 1
continue
print(i)
when i = 3, above condition executes, does the operation i=i+1 and then continue, which looks to be confusing you, so what continue does is it will jump the execution to start the next iteration without executing the code after it in the loop, i.e. print(i) would not be executed.
This means that for every iteration of i the loop will print i, but when i = 3 the if condition executes and continue is executed, leading to start the loop for next iteration i.e. i=4, hence the 3 is not printed.
In the provided code when you try to use i in a for loop with range, it always changes to the number provided by range in the function without bothering to look at the increment made to i. so basically if you try list(range(0, 10)) this will give you [0, 2, 3, 4, 5, 6, 7, 8, 9]. so for goes through that list one by one without thinking if any changes were made to i or not.
which if seen
loop_1: i=0
loop_2: i=1
loop_3: i=2
loop_4: i=3 (here now you increment value by 1), i=4
loop_5: i=4 (but the for loop was going though the list from range function so the change didn't do anything)
loop_6: i=5 (and so on until 9)
iis replaced with the next value from therangeindependent of any earlier change to it's value.