Code Explanation:
def gen():
This defines a generator function named gen.
Unlike a regular function that returns values once and exits, this function will use yield, making it a generator.
When called, it returns a generator object that can produce a sequence of values over time.
i = 0
Inside the function, you initialize a variable i to 0.
This will be the starting value of your counter.
while True:
This creates an infinite loop.
It means the code inside this block will keep repeating forever (unless you break it manually or stop calling next()).
The generator is designed to produce values endlessly.
yield i
This is the core of a generator.
yield means: “pause here and return the value of i to the caller.”
After yielding, the generator’s state is saved — including the current value of i, and where it was in the code.
i += 1
After yielding i, we increment i by 1.
So next time the generator resumes, it will yield the next number.
This makes the generator produce 0, 1, 2, 3, ... one at a time.
g = gen()
Now you call the generator function, which returns a generator object.
The function body doesn't run yet — it just prepares the generator to be used.
Variable g now holds that generator object.
print(next(g), next(g), next(g))
You are calling next(g) three times.
Each call resumes the generator, runs until the next yield, and returns the value:
next(g) → i = 0, yields 0, then i becomes 1
next(g) → resumes at i = 1, yields 1, then i becomes 2
next(g) → resumes at i = 2, yields 2, then i becomes 3
These three values are printed on one line, separated by spaces.
Final Output:
0 1 2
0 Comments:
Post a Comment