4

Okay, so is there a way to return a value from a function - the way return does - but not stop the function - the way return does?

I need this so I can keep returning values every so often. (Delays provided by time.sleep() or whatever.)

Charles Noon
  • 559
  • 3
  • 10
  • 16
  • 5
    [`yield`](http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained) may be what you're looking for – TerryA Sep 02 '13 at 07:30
  • http://stackoverflow.com/questions/231767/the-python-yield-keyword-explained – rags Sep 02 '13 at 07:33
  • 1
    If you want to return values on a timer, `yield` might not help you. You may need a thread-based or event-driven solution. – user2357112 Sep 02 '13 at 07:40

2 Answers2

6

I think you are looking for yield. Example:

import time

def myFunction(limit):
    for i in range(0,limit):
        time.sleep(2)
        yield i*i

for x in myFunction(100):
    print( x )
Balthazar Rouberol
  • 6,822
  • 2
  • 35
  • 41
Mario Rossi
  • 7,651
  • 27
  • 37
0
def f():
  for i in range(10):
     yield i

g = f().next

# this is if you actually want to get a function
# and then call it repeatedly to get different values
print g()
print g()

print

# this is how you might normally use a generator
for i in f():
  print i

Output:

0
1

0
1
...
9
Vlad
  • 18,195
  • 4
  • 41
  • 71
  • I really don't understand what your answer contributes. And I'm not sure your even **read** the question. Can you please comment on this? – Mario Rossi Sep 02 '13 at 07:47
  • I felt like the OP's question focused on having a function that did what he wanted, so I provided an example which gave you a function you could use more than once, in order to get those different return values. It's an addition to the classic generator example that you provided. – Vlad Sep 02 '13 at 13:46