Code Explanation:
1. Function Definition: infinite()
def infinite():
This defines a generator function named infinite.
It doesn't take any arguments.
Unlike a regular function that returns once, a generator uses yield to produce a sequence of values lazily—one at a time.
2. Initialize a Counter Variable
i = 0
Inside the function, i is initialized to 0.
This will be the starting value of the infinite sequence being generated.
3. Infinite Loop
while True:
This creates an infinite loop.
True is always true, so the loop will never stop unless the program is interrupted.
4. Yield the Current Value of i
yield i
This pauses the function and sends the current value of i to the caller.
Unlike return, yield doesn’t terminate the function; it pauses it and remembers the state.
The next time the generator is resumed, execution continues right after yield.
5. Increment the Counter
i += 1
After yielding, i is increased by 1.
So the next time the loop runs, it will yield the next number in sequence.
6. Create the Generator Object
g = infinite()
Here, the generator function infinite() is called, but it doesn’t execute immediately.
Instead, it returns a generator object stored in the variable g.
This object can be used to fetch values using next().
7. Loop to Get First 3 Values
for _ in range(3):
print(next(g))
This loop runs 3 times (i.e., _ takes values 0, 1, 2 but the _ means we don’t care about the loop variable).
On each iteration:
next(g) resumes the generator and returns the next value from it.
That value is printed.
Output of the Code
0
1
2
Download Book - 500 Days Python Coding Challenges with Explanation
.png)

0 Comments:
Post a Comment