Exercise: Python

Questions for: Generators

How does the generator.send(value) method differ from yield value when used with a generator?
A:
They have the same effect on the generator
B:
generator.send(value) sends a value into the generator, while yield value yields a value from the generator
C:
yield value sends a value into the generator, while generator.send(value) yields a value from the generator
D:
generator.send(value) stops the generator, while yield value continues the generator's execution
Answer: B
generator.send(value) is used to send a value into the generator, while yield value is used to yield a value from the generator.
What is the purpose of the itertools.count(start, step) function when used with generators?
A:
It generates an infinite sequence of numbers starting from the specified value
B:
It stops the generator after one iteration
C:
It initializes the generator with the provided start value
D:
It generates a sequence of numbers with a specified step value
Answer: A
itertools.count(start, step) generates an infinite sequence of numbers starting from the specified value, with an optional step value.
What does the itertools.takewhile() function do when used with a generator?
A:
It takes the first element from the generator
B:
It takes elements until a certain condition is false
C:
It stops the generator after one iteration
D:
It filters elements based on a specified condition
Answer: B
itertools.takewhile() takes elements from the generator until the specified condition becomes false, after which it stops yielding elements.
How does the generator.throw(ValueError, "message") method differ from raise ValueError("message") when used with a generator?
A:
They have the same effect on the generator
B:
generator.throw(ValueError, "message") is used to raise an exception inside the generator, while raise ValueError("message") is used outside the generator
C:
raise ValueError("message") is used to raise an exception inside the generator, while generator.throw(ValueError, "message") is used outside the generator
D:
generator.throw(ValueError, "message") stops the generator, while raise ValueError("message") continues the generator's execution
Answer: B
generator.throw(ValueError, "message") is used to raise an exception inside the generator, while raise ValueError("message") is used outside the generator to raise an exception.
What is the purpose of the itertools.dropwhile() function when used with generators?
A:
It drops the first element from the generator
B:
It skips elements until a certain condition is false
C:
It stops the generator after one iteration
D:
It filters elements based on a specified condition
Answer: B
itertools.dropwhile() skips elements from the generator until the specified condition becomes false, after which it yields the remaining elements.
Ad Slot (Above Pagination)
Quiz