I have a for loop that checks a series of conditions. On each iteration, it should yield output for only one of the conditions. The final yield is a default, in case none of the conditions are true. Do I have to put a continue after each block of yields?
def function():
for ii in aa:
if condition1(ii):
yield something1
yield something2
yield something3
continue
if condition2(ii):
yield something4
continue
#default
yield something5
continue
When the Python yield statement is hit, the program suspends function execution and returns the yielded value to the caller. (In contrast, return stops function execution completely.)
yield in Python can be used like the return statement in a function. When done so, the function instead of returning the output, it returns a generator that can be iterated upon. You can then iterate through the generator to extract items. Iterating is done using a for loop or simply using the next() function.
Description. Python yield returns a generator object. Generators are special functions that have to be iterated to get the values. The yield keyword converts the expression given into a generator function that gives back a generator object.
What Is Yield In Python? The Yield keyword in Python is similar to a return statement used for returning values or objects in Python. However, there is a slight difference. The yield statement returns a generator object to the one who calls the function which contains yield, instead of simply returning a value.
NO, yield doesn't imply continue, it just starts at next line, next time. A simple example demonstrates that
def f():
for i in range(3):
yield i
print i,
list(f())
This prints 0,1,2 but if yield continues, it won't
Instead of using the continue
statement I would suggest using the elif
and else
statments:
def function():
for ii in aa:
if condition1(ii):
yield something1
yield something2
yield something3
elif condition2(ii):
yield something4
else: #default
yield something5
This seems much more readable to me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With