def my_generator():
for i in range(3):
yield i
gen = my_generator()
print(next(gen))
print(next(gen))
Explanation:
- my_generator():
- This defines a generator function that yields values from 0 to 2 (range(3)).
- gen = my_generator():
- Creates a generator object gen.
- print(next(gen)):
- The first call to next(gen) will execute the generator until the first yield statement.
- i = 0 is yielded and printed: 0.
print(next(gen)): - The second call to next(gen) resumes execution from where it stopped.
- The next value i = 1 is yielded and printed: 1.
Output:
0
1
If you call next(gen) again, it will yield 2. A fourth call to next(gen) would raise a StopIteration exception because the generator is exhausted.
0 Comments:
Post a Comment