Omit in for loop in Python

Viewed 72

I have a function to move between the given range of values, but I would like to add in my function a parameter that will be an array which would contain the numbers which must be skipped while my function run iteration

my function:

    nums = []

    def loopIteration(minValue, maxValue):
        minValue += 1
        for i in range(maxValue-minValue+1):
            num = i+minValue
            nums.append(Num('numbers_{}'.format(i)))

#function call
loopIteration(4,25)

i want to add in my function call an parameter like this:

loopIteration(4,25,[8,9,16])

thanks for any answers :)

2 Answers

You can use continue to skip certain is:

def loopIteration(minValue, maxValue, skip=set()):
    for i in range(minValue + 1, maxValue + 1):
        if i in skip:
            continue
        cells.append(Cell("numbers_{}".format(i)))

Continue is a Python syntax which would allow you to pass iteration in a for loop. Usually, continue can make it quite hard to follow flow later on, if you ever wish to look back on your script. Here is what you could do:

def loopInteration(minValue, maxValue, skipNums):
   for number in range(maxValue-minValue+1):
       if number in skipNums:
           continue
       num = i+minValue
       nums.append(Num("numbers_{}".format(i)))

loopIteration(4,25,[NUMBERS HERE])
Related