user13209860
user13209860

Reputation:

Loop behavior in python

for i in range(10):
    if i == 2:
        i += 2
    print(i,end=",")

I want to print 0,1,4,5,6,7,8,9 but it is printing 0,1,4,3,4,5,6,7,8,9. Is there any way to fix this??

Upvotes: 0

Views: 42

Answers (3)

nocibambi
nocibambi

Reputation: 2431

Based on the overall logic, this might also do the trick.

for i in range(10):
    if i not in [2, 3]:
        print(i,end=",")

Upvotes: 0

Teejay Bruno
Teejay Bruno

Reputation: 2159

This should do it:

for i in range(8):
  if i >= 2 :
    i += 2
  print(i,end=",")

Upvotes: 0

user2390182
user2390182

Reputation: 73450

Use a while-loop:

i = 0
while i < 10:
    if i == 2:
        i += 2
    print(i, end=",")
    i += 1

The for for-loop will rebind the loop variable in each iteration. The while-loop gives you more control.

Upvotes: 1

Related Questions