Search code examples
pythonloopsreturn

returning value without breaking a loop


I intend to make a while loop inside a defined function. In addition, I want to return a value on every iteration. Yet it doesn't allow me to iterate over the loop. Here is the plan:

def func(x):
    n=3
    while(n>0): 
        x = x+1  
        return x

print(func(6))    

I know the reason to such issue-return function breaks the loop. Yet, I insist to use a defined function. Therefore, is there a way to somehow iterate over returning a value, given that such script is inside a defined function?


Solution

  • When you want to return a value and continue the function in the next call at the point where you returned, use yield instead of return.

    Technically this produces a so called generator, which gives you the return values value by value. With next() you can iterate over the values. You can also convert it into a list or some other data structure.

    Your original function would like this:

    def foo(n):
      for i in range(n):
        yield i
    

    And to use it:

    gen = foo(100)
    print(next(gen))
    

    or

    gen = foo(100)
    l = list(gen)
    print(l)
    

    Keep in mind that the generator calculates the results 'on demand', so it does not allocate too much memory to store results. When converting this into a list, all results are caclculated and stored in the memory, which causes problems for large n.