Home > Software design >  returning value without breaking a loop
returning value without breaking a loop

Time:01-05

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?

CodePudding user response:

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.

CodePudding user response:

Depending on your use case, you may simply use print(x) inside the loop and then return the final value.

If you actually need to return intermediate values to a caller function, you can use yield.

CodePudding user response:

You can create a generator for that, so you could yield values from your generator.

Example:

def func(x):
    n=3
    while(n>0): 
        x = x 1  
        yield x
func_call = func(6)  # create generator
print(next(func_call)) # 7
print(next(func_call)) # 8
  • Related