Examveda
Examveda

How do you define a generator function in Python?

A. Using the generator keyword

B. Using the def keyword and yield statement

C. Using the gen keyword

D. Using the function keyword

Answer: Option B

Solution(By Examveda Team)

The correct answer is Option B: Using the def keyword and yield statement.
To define a generator function in Python, you use the def keyword like a regular function, but instead of returning a value using the return keyword, you use the yield statement to yield a value. The yield statement suspends the function's execution and returns the yielded value to the caller. Subsequent calls to the generator function continue execution from where it was previously suspended. This allows generator functions to generate values lazily and efficiently, one at a time, as needed.

This Question Belongs to Python Program >> Generators And Iterators

Join The Discussion

Related Questions on Generators and Iterators