Code Explanation:
1. Generator Function Definition
def gen():
for i in range(2):
yield i
A generator function gen() is defined.
It contains a for loop: for i in range(2) → this will loop over values 0 and 1.
yield i will pause the function and return the value of i.
2. Create Generator Object
g = gen()
This creates a generator object named g.
The generator is ready, but has not started executing yet.
3. First next(g)
print(next(g))
Starts the generator.
Enters the loop: i = 0.
yield 0 returns 0.
So it prints:
0
4. Second next(g)
print(next(g))
Resumes the generator after the first yield.
Next loop iteration: i = 1.
yield 1 returns 1.
So it prints:
1
Final Output
0
1


0 Comments:
Post a Comment