Code Explanation:
1. Defining a Generator Function
def process():
- Defines a function named process().
- This function contains yield statements, so Python treats it as a Generator Function.
- Unlike a normal function, a generator produces values one at a time instead of returning all values together.
2. First Yield Statement
yield 10
- The yield keyword produces the value 10.
- The function pauses its execution at this point.
- Its current execution state is saved.
- When the generator is called again, execution resumes from where it stopped.
3. Second Yield Statement
yield 20
- Produces the next value, which is 20.
- The generator pauses again.
- It remembers its current position and waits for the next request.
4. Return Statement
return 30
- Ends the generator function.
- The value 30 is not yielded as a normal generator output.
- Instead, it becomes the value carried by the StopIteration exception.
- Once this statement executes, the generator is exhausted.
Important: yield produces values, whereas return terminates the generator.
5. Creating the Generator Object
g = process()
- Calls the generator function.
- Creates a generator object and stores it in g.
- The function body does not execute immediately.
- Execution starts only when we request a value using next().
6. Getting the First Value
print(next(g))
- next() starts executing the generator.
- Execution reaches yield 10.
- The generator pauses and returns 10.
- print() displays the value.
Output:
10
7. Getting the Second Value
print(next(g))
- Calls next() again on the same generator.
- Execution resumes after the first yield.
- It reaches yield 20.
- The generator pauses again and returns 20.
Output:
20
8. Handling Generator Exhaustion
print(next(g, "Finished"))
- Calls next() for the third time.
- The generator resumes after yield 20.
- It executes return 30 and terminates.
- Python raises StopIteration, carrying 30 as its value.
- However, next(g, "Finished") uses "Finished" as the default value when the generator is exhausted.
- Therefore, it prints "Finished" instead of raising an unhandled exception.
Output:
Finished
Final Output
Correct Answer
10
20
Finished
.png)

0 Comments:
Post a Comment