Question

function:

def function_1(value):
    if value < 5:
        continue
    else:
        print "value: ", value

loop:

for value in xrange(10):
    function_1(value)

in for loop above, if value is less than 5, function_1 will make the for loop skip to next iteration, else it will print the value. How can I skip an iteration step with the help of a function inside the loop as above?

Was it helpful?

Solution

A function doesn't know if it is being called inside a loop and certainly cannot use continue or break to influence that loop.

You'll have to use a different means of communicating here. Use exceptions or return a boolean to indicate to the loop code it needs to skip to the next iteration.

Using an exception:

for value in xrange(10):
    try:
        function_1(value)
    except ExceptionRaisedByFunction1:
        # the frobnar failed to foozle the baz
        continue

would signal an exceptional situation in the function, indicating that the current value isn't suitable and the rest of the iteration can be skipped, for example.

You could also consider using a generator function instead, to filter your iterable instead:

def filter_function(iterable):
    for value in iterable:
         if value >= 5:
              print "value: ", value
              yield value

for value in filter_function(xrange(10)):
    # do something with value

Here the generator only yields values that are 5 or over, so the for loop never needs to use continue as the values below 5 are never seen.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top