-1

I have a for loop in range(100).

Whenever I find a number that does satisfy a condition, it should skip a loop certain number of times

for i in range(2,100):
    if i %2 != 0:
        i = i+3

Expected results should be:


2
3
6
7
10
11
.
.
.
.
.
S.K
  • 1
  • 3

5 Answers5

0

In my understanding this is what you want to do. But its not the output you desire. But I guess your expected output is not the output of your logic.

i = 2
while i<100:
    print(i)
    if i % 2 != 0:
        i += 3
    else:
        i += 1

Outputs:

2
3
6
7
10
11
...
luigigi
  • 4,146
  • 1
  • 13
  • 30
  • Thank you, sorry my problem statement was confusing, How can we get the same in for loop ? – S.K Oct 24 '19 at 09:26
0

A for-loop does not allow you to skip multiple cycles. You can only use

  • continue to skip the rest of the current cycle
  • break to skip all remaining cycles and exit the loop

What you need is a while-loop. Where a for-loop defines a number that is incremented from a starting value up to a limit, a while-loop only needs an exit-condition.

Try this:

i = 2
while i < 100:
  if i % 2 == 0:
    i += 4
  else:
    i += 1
fafl
  • 7,222
  • 3
  • 27
  • 50
0
 j = 0
 for i in range(j,100):
    if i%2 !=0:
      j = i+3
      continue
    print(j)

output: 0 4 6 8 10 12 14 16 18 20 . . . .

0

Actually i = i+3 has no effect in a for loop. you may think that i becomes 2+3=5 but in the next iteration i will be 3. You need to use a hile loop for this. This will do the trick for you:

i = 2
while i <= 100:
    print(i)
    i = (i + 3) if i % 2 != 0 else (i + 1)
Kostas Charitidis
  • 2,991
  • 1
  • 12
  • 23
0

Solution with a for loop (although I think a while loop is better for this):

skipping = 0
for i in range(2, 100):
    if skipping:
        skipping -= 1
        continue
    if i % 2 != 0:
        print(i)
        skipping = 2
    else:
        print(i)

Output:

2
3
6
7
10
11
...
Dan
  • 1,575
  • 1
  • 11
  • 17