Code Explanation:
1. Generator Function Definition
def gen():
for i in range(3):
yield i*i
def gen():
Defines a generator function named gen.
for i in range(3):
A loop that iterates i from 0 to 2 (i.e., 0, 1, 2).
yield i*i
This pauses the function and produces the square of i.
Unlike return, yield allows the function to resume where it left off. This makes gen() a generator.
2. Creating a Generator Object
g = gen()
Calling gen() doesn't run it immediately.
It returns a generator object g, which is an iterator that will compute values on demand using yield.
3. First Call to next(g)
print(next(g))
Starts executing the gen() function.
i = 0, so it yields 0*0 = 0.
Output: 0
4. Second Call to next(g)
print(next(g))
Resumes where it left off in gen().
Now i = 1, so it yields 1*1 = 1.
Output: 1
5. Resetting the Generator
g = gen()
A new generator object is created and assigned to g.
The previous state of the original g is discarded.
Now this new g starts again from the beginning.
6. Third Call to next(g)
print(next(g))
Executes the new generator from the start.
i = 0 again, so it yields 0*0 = 0.
Output: 0
Final Output
0
1
0
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment