Explanation:
Function Definition (countdown(n)):
The function countdown(n) is a generator because it contains the yield statement.
A generator function produces a sequence of values lazily, meaning values are generated on-demand instead of all at once.
While Loop (while n > 0):
The function keeps running as long as n > 0.
Inside the loop, yield n returns the current value of n and pauses execution.
The n -= 1 statement decreases n by 1 in each iteration.
Calling the Generator (gen = countdown(3)):
This does not execute the function immediately. Instead, it creates a generator object.
Converting Generator to List (print(list(gen))):
The list(gen) forces the generator to produce all its values and store them in a list.
When list() iterates over gen, it calls next(gen) repeatedly until the generator is exhausted.
Output:
[3, 2, 1]
0 Comments:
Post a Comment