Let\'s say I write a for loop that will output all the numbers 1 to x:
x=4
for number in xrange(1,x+1):
print number,
#Output:
1
2
3
4
What you want is is called a Generator:
def counter(x):
for number in xrange(1,x+1):
yield number
You would then use it like this:
c = counter(5)
next(c) # 1
next(c) # 2
You could also consume the entire generator by doing:
xs = list(c) # xs = [1, 2, 3, 4, 5]
See: http://docs.python.org/2/tutorial/classes.html#generators for more information.
The return statement in Python returns form the function and does not save any state. Every time you call the function a new stack frame is created. yield on the other hand is (more or less) Python's equivilent of continutations
return
does exactly like the keyword's name implies. When you hit that statement, it returns and the rest of the function is not executed.
What you might want instead is the yield
keyword. This will create a generator function (a function that returns a generator). Generators are iterable. They "yield" one element each time the yield
expression is executed.
def func():
for x in range(10):
yield x
generator = func()
for item in generator:
print item
Once return
in a function, the function ends and the remaining code won't be excuted any more.
Your second solution is good and if you want better solution, you can use generator:
def counter(x):
for number in xrange(1,x+1):
yield number
And then you can use it like this:
>>> for i in counter(5):
... print i
...
1
2
3
4
5