“Return” in Function only Returning one Value

前端 未结 3 1800
萌比男神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:20

    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
    

提交回复
热议问题