-2

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)
3
  • 1
    this works just like it should be, please give the code which does not work Commented Jan 28, 2021 at 4:22
  • 2
    On every iteration i is replaced with the next value from the range independent of any earlier change to it's value. Commented Jan 28, 2021 at 4:24
  • You can try debugging to understand the flow. Commented Jan 28, 2021 at 4:37

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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)

1 Comment

That really makes sense @xcodz-dot. we can use a while loop in this case.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.