Complete the generator evens() so that it yields 2, 4, 6, … forever. The program prints the first n values.
What to build
A generator that never runs out.
Requirements
- Complete
evens()so that it yields 2, 4, 6 and so on, forever. - Leave the rest of the program as it is.
Input
One whole number n from 1 to 1000.
Output
The first n even numbers, one per line.
Constraints
n is from 1 to 1000.
Example
Input:
3
Output:
2
4
6
Why it works
The while True is safe because the generator pauses at each yield and only continues when another value is requested.
Examples
Example 1 · Input
3
Expected output
2 4 6
Example 2 · Input
1
Expected output
2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Use while True with yield inside.
Hint 2
yield hands out one value and pauses until next() asks again.
Solution
Show one correct solution (try it yourself first)
def evens():
value = 2
while True:
yield value
value += 2
n = int(input())
gen = evens()
for _ in range(n):
print(next(gen))