“Return” in Function only Returning one Value

前端 未结 3 1794
萌比男神i
萌比男神i 2021-01-06 11:40

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

3条回答
  •  情歌与酒
    2021-01-06 12:19

    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

提交回复
热议问题