Step-by-Step Execution:
-
Function Definition
-
This defines a generator function.
-
The keyword yield makes gen() return a generator object, not a regular value.
-
-
Create Generator
-
Now, g is a generator object that will produce values when next(g) is called.
-
-
First next(g)
-
This starts the generator.
-
It runs the function up to the first yield, which is:
-
So it yields 10, and pauses.
-
-
Second next(g)
-
The generator resumes after the yield.
-
But there's nothing left in the function.
-
So it raises a StopIteration exception.
-
What Happens When You Run It?
-
First next(g) → works, returns 10.
-
Second next(g) → raises:
✅ Visual Summary:
✅ Final Advice:
If you want to handle it safely:


0 Comments:
Post a Comment