“Return” in Function only Returning one Value

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

    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
    

提交回复
热议问题