Code Explanation:
1. Function Definition
def early_exit():
This line defines a function called early_exit.
It's a generator function because it will use the yield keyword inside.
2. Start of the Loop
for i in range(10):
This is a for loop that iterates over numbers from 0 to 9 (i.e., range(10)).
i takes on each value in the range one at a time.
3. Early Exit Condition
if i > 3:
return
This if statement checks if i is greater than 3.
If true, it calls return, which exits the function entirely (not just the loop).
Since it's a generator function, this also means no more values will be yielded.
4. Yield Statement
yield i
This line is executed only if i <= 3.
It yields the value of i to the caller.
This is what makes the function a generator — it returns values one at a time and remembers its state between calls.
5. Calling the Generator and Converting to List
print(list(early_exit()))
This calls the early_exit() generator and wraps it with list(), which:
Iterates through all values the generator yields.
Collects them into a list.
The output will be printed.
Final Output
[0, 1, 2, 3]
Download Book - 500 Days Python Coding Challenges with Explanation


0 Comments:
Post a Comment