Following is a sample code where use of yield function is shown. create_generator() function is defined which basically iterates over a range of numbers 1 to 4. Here the value a and b is summed up and incremented in every iteration.
In the following steps, when this same function create_generator() is used to provide range of values for loop (for i in create_generator() ) every time the program flow stops at yield statement and provides value to i. This value is printed. Loop continues until the loop inside create_generator() completes.
It can also be seen in the following code where each step is printed using next() functionality. The last print statement is commented. Because, at that point there is no further value produced by generator function. It throws error.
Both the outputs (with and without comment part are provided). you can try it out too ....
In the following steps, when this same function create_generator() is used to provide range of values for loop (for i in create_generator() ) every time the program flow stops at yield statement and provides value to i. This value is printed. Loop continues until the loop inside create_generator() completes.
It can also be seen in the following code where each step is printed using next() functionality. The last print statement is commented. Because, at that point there is no further value produced by generator function. It throws error.
Both the outputs (with and without comment part are provided). you can try it out too ....
#__author__ = 'Sumant'
# use of yield functionality of python def create_generator(): a = 1
b = 10
for count in range(1, 5):
yield a + b a += 1
b += 1 for value in create_generator(): print value print "going step by step ..."
xx = create_generator() print xx.next() print xx.next() print xx.next() print xx.next()
#print xx.next()
-------------------------------------------------
OUTPUT (with last line commented)
-------------------------------------------------
11 13 15 17
going step by step ... 11 13 15 17 Process finished with exit code 0
-------------------------------------------------
OUTPUT (uncomment last line)
-------------------------------------------------
11 13 15 17 going step by step ... 11 13 15 17 Traceback (most recent call last): File ".../demo_yield.py", line 22, in <module> print xx.next() StopIteration Process finished with exit code 1
No comments:
Post a Comment