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
source to share
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, itStopIteration
will be raised, otherwise the value will be returned.
source to share