Call a function on the loop line and store the return value of a variable so you can use it later in the loop?

I want to do something like the following:

while myFunc() as myVar:
    print myVar

      

Basically, just call a function on the loop line that will return a value and continue the loop based on that value, but I would also like to be able to use that value in a loop and I wouldn't have to call the function the 2nd time.

What I would like to avoid:

while myFunc():
    myVar = myFunc()
    print myVar

      

+3


source to share


2 answers


You can accomplish this with a two-parameter version of the iter()

built-in function:

for myVar in iter(myFunc, sentinel):
    print myVar

      

This is equivalent to the following:



while True:
    myVar = myFunc()
    if myVar == sentinel:
        break
    print myVar

      

From docs for iter()

:

If the second argument, sentinel, is given, then o must be a callable. The iterator created in this case will call o with no arguments for each call to its method next()

; if the return value is equal to sentinel, it StopIteration

will be raised, otherwise the value will be returned.

+3


source


Use a generator that returns this value.

for myVal in myFunc():
 print myVal

      



This is combined with the yield statement.

0


source







All Articles