Home > database >  How to use Loop inside Function corectly
How to use Loop inside Function corectly

Time:11-16

i want use loop correctly inside function

This is my code :

def test():
    for i in range(1,10):
        return i


def check():
    print(test())
check()

output is 1

i want to full iteration output : 1 ,2,4....10

CodePudding user response:

When you return inside a function, it immediately terminates the function and returns the specified value. This means that it goes into the for loop and returns 1, then stops running. One way to get around this is to use the yield keyword instead of return.

def test():
    for i in range(1, 10):
        yield i

This will make test() a generator, which can then be printed in check by unpacking its values.

def check():
    print(*test())

Alternative ways of doing this would be to return a list in test() or to simply print the values within test() itself.

CodePudding user response:

In Python (as with almost all programming languages), functions can only return once (ish). As soon as Python encounters return, it'll exit the function.

Python does have a feature called "generators", though: with the yield keyword, you can (sort of) return more than once:

def test():
    for i in range(1,10):
        yield i

To expand those values to the print function's arguments, use * like so:

def check():
    print(*test())
>>> check()
1 2 3 4 5 6 7 8 9
>>> sum(test())
45

wim points out that you can sometimes return more than once from a function – but later return statements will "replace" the return value from earlier ones.

>>> def f():
...     try:
...         return 1
...     finally:
...         return 2
...
>>> f()
2

Unfortunately, CPython's optimising this too much for me to make sense of the dis bytecode decompilation; I have no idea how this works under the hood.

CodePudding user response:

If you want to return all the values in the range you can do something like this:

def test():
    return [i for i in range(1,10)]


def check():
    print(test())
check()
  • Related