How to skip a for loop by X amount and continue for Y amount, then repeat

Viewed 184

Being struggle with this for a while but how am I able to skip for loops in python by X and continue for Y then repeat.

For example:

# This loop should loop until 99, but after it reaches a number that is a multiple of 10 e.g. 10,20,30 etc it should continue for 5 iterations, then skip to next multiple of 10.
# E.g 0,1,2,3,4,5,10,11,12,13,14,15,20,21,22,23,24,25,30...etc
for page_num in range(100):
    # Use page_num however
5 Answers

Modify the loop to use a step of 10, and add a sub-loop to have iterations that break off after the 5th element.

for j in range(0,100,10):
    for page_num in range(j, j+6):
         # use page_num

Use continue to skip the rest of the loop if the digit in units place is greater than 5.

skip_after = 5
for page_num in range(100):
    if page_num % 10 > skip_after: continue
    # ... Do the rest of your loop 
    print(page_num)

page_num % 10 uses the modulo % operator to give the remainder from dividing page_num by 10 (which is the digit in the units place).

Output (joined into a single line for readability):

0 1 2 3 4 5 10 11 12 13 14 15 20 21 22 23 24 25 30

Using itertools.filterfalse

from itertools import filterfalse

for x in (filterfalse(lambda x: (x % 10) > 5, range(0, 100))):
    print(x, end=' ')

Output:

0 1 2 3 4 5 10 11 12 13 14 15 20 21 22 23 24 25 30 31 32 33 34 35 40 41 42 43 44 45 50 51 52 53 54 55 60 61 62 63 64 65 70 71 72 73 74 75 80 81 82 83 84 85 90 91 92 93 94 95 

I would recommend list comprehension. Im not positive if this is the complete answer but I would do it as:

def find_divisors_2(page_num):
    """
    You can insert an algorithmic phrase after if and it will produce the answer.
    """
    find_divisors_2 = [x for x in range(100) if (Insert your algorithm)]
    return find_divisors_2

You can directly modify the value of page_num inside the for loop with a certain condition:

for page_num in range(100):
    if str(page_num)[-1]=="6":
        page_num += 4
    print(page_num)
Related