Code Explanation:
1. Generator Function Definition
def gen():
for i in range(2):
yield i
What this does:
This defines a generator function named gen().
Inside it, there’s a for loop: for i in range(2) → it will loop over 0 and 1.
The yield keyword is used instead of return.
Key Concept:
A generator function doesn't run immediately when called.
It returns a generator object, which can be iterated using next().
yield pauses the function and remembers its state, so it can resume from where it left off.
2. Create Generator Object
g = gen()
What this does:
Calls the gen() function.
Instead of executing the function body right away, Python returns a generator object.
This object can be used to get values from the generator one at a time using next().
g is now a generator that will yield 0, then 1, then stop.
3. First next() Call
print(next(g))
What this does:
Starts executing the gen() generator.
Enters the loop: i = 0.
Hits yield i, which yields 0.
The function is paused right after yielding 0.
Output:
0
4. Second next() Call
print(next(g))
What this does:
Resumes the generator from where it left off.
Next loop iteration: i = 1.
Yields 1.
Pauses again after yielding.
Output:
1
Final Output
0
1
.png)

0 Comments:
Post a Comment