Code Explanation:
1. Function Definition
def numbers():
This line defines a generator function named numbers.
In Python, any function containing a yield statement becomes a generator function.
2. Loop Inside Generator
for i in range(3):
yield i
range(3) generates the sequence: 0, 1, 2.
For each value i, the generator pauses and yields i instead of returning.
After yielding, the function’s state is saved, and it resumes from the same point on the next next() or iteration.
3. Generator Creation
n = numbers()
This calls the generator function and stores the resulting generator object in the variable n.
No code inside numbers() runs yet—nothing is printed or executed until iteration begins.
4. Iterating Over Generator
for i in n:
print(i)
This for loop automatically calls next(n) repeatedly until the generator is exhausted.
On each loop:
The generator yields i → print(i) prints it.
Final Output:
0
1
2
.png)

0 Comments:
Post a Comment