Exercise: Generators
Questions for: Generators
What happens if the
generator.throw(ValueError) method is called without specifying an exception value?
A:
It raises a
ValueError with a default message
B:
It raises a
TypeError
C:
It has no effect on the running generator
D:
It raises a
StopIteration exception
Answer: B
Calling
generator.throw(ValueError) without specifying an exception value raises a TypeError, as the exception value is mandatory.
How does the
generator.throw(StopIteration, value) method affect a running generator?
A:
It stops the generator and raises a
StopIteration exception with the specified value
B:
It continues the generator's execution with the specified value
C:
It has no effect on the running generator
D:
It raises a
ValueError with the specified value
Answer: A
generator.throw(StopIteration, value) stops the generator and raises a StopIteration exception with the specified value.Discuss About this Question.
How does the
generator.throw(GeneratorExit) method differ from generator.close()?
A:
They are equivalent in functionality
B:
generator.throw(GeneratorExit) raises a GeneratorExit exception in the generator, while generator.close() terminates the generator
C:
generator.close() raises a GeneratorExit exception, while generator.throw(GeneratorExit) terminates the generator
D:
generator.throw(GeneratorExit) and generator.close() are not valid methods
Answer: B
generator.throw(GeneratorExit) raises a GeneratorExit exception in the generator, indicating that the generator should be closed. generator.close() terminates the generator without raising an exception.Discuss About this Question.
How does the
itertools.count() function differ from using range()?
A:
They are equivalent in functionality
B:
itertools.count() generates an infinite sequence, while range() creates a finite sequence
C:
range() generates an infinite sequence, while itertools.count() creates a finite sequence
D:
itertools.count() raises a StopIteration exception when exhausted, while range() does not
Answer: B
itertools.count() generates an infinite sequence of numbers, while range() creates a finite sequence of numbers.Discuss About this Question.
How does the
generator.throw() method differ from the generator.close() method?
A:
They are equivalent in functionality
B:
generator.throw() raises a specific exception in the generator, while generator.close() terminates the generator
C:
generator.close() raises a StopIteration exception, while generator.throw() terminates the generator
D:
generator.throw() raises a StopIteration exception, while generator.close() terminates the generator
Answer: B
generator.throw() raises a specific exception in the generator, while generator.close() terminates the generator by raising a GeneratorExit exception.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.