1

I know it is not possible. Return will exit it. Is there a way to make it possible. I have while loop and it counts the values. I want to return the value from the while loop and use it for further processing and get back to the while loop again and continue where it stopped. I know the return will exit the loop. How to make it possible.

Here's the sample code:

import datetime
import time
def fun2(a):
    print("count:", a)
def fun():
    count = 0
    while 1:
        count = count+1
        time.sleep(1)
        print(count)
        if count == 5:
            return count
a = fun()
fun2(a)

My Output:

1
2
3
4
5
count: 5

Required Output:

1
2
3
4
5
count: 5
6
7
8
9
and goes on....
Paul Steven
  • 41
  • 1
  • 7

1 Answers1

12

Seems like you need a generator. The generator will remember the value and yield it when it is divisible by 5 (which I assumed by looking at your output) on calling next, and will remember the older state, until you call next on it again. Also note that this is an infinite generator.

def fun():
    count = 0
    while True:
        count = count+1
        print('inside fun', count)
        if count % 5 == 0:
            yield count

f = fun()
print(next(f))
print(next(f))

The output will be

inside fun 1
inside fun 2
inside fun 3
inside fun 4
inside fun 5
5
inside fun 6
inside fun 7
inside fun 8
inside fun 9
inside fun 10
10
Devesh Kumar Singh
  • 20,259
  • 5
  • 21
  • 40