Code Explanation:
1) def gen():
Defines a generator function named gen.
Unlike a normal function, it uses yield, meaning calling it will return a generator object that produces values one at a time.
2) for i in range(3):
Loop from i = 0 to i = 2 (range(3) gives [0, 1, 2]).
3) yield i * i
Each loop iteration yields the square of i instead of returning it once.
So calling gen() produces values: 0, 1, 4.
4) g = gen()
Calls the generator function.
No code inside gen runs yet — instead, we get a generator object assigned to g.
5) print(next(g))
next(g) starts the generator and runs until the first yield.
For i = 0, it yields 0 * 0 = 0.
Prints:
0
6) print(sum(g))
Now the generator g continues from where it left off.
Remaining values to yield:
i = 1 → 1 * 1 = 1
i = 2 → 2 * 2 = 4
So sum(g) = 1 + 4 = 5.
Prints:
5
Final Output
0
5
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment