Command Palette

Search for a command to run...

Hectal
Phase 9: Iterators, Generators and Decorators
Python · Exercise 2 of 6 PreviousNext
Intermediate

Write an iterator class

Write a class Evens whose constructor takes a limit. Looping over Evens(limit) produces the even numbers from 0 up to but not including limit.

It must be a real iterator: write __iter__ (returning self) and __next__ (raising StopIteration at the end). Then print list(Evens(7)).

What Check tests

  1. list(Evens(7)) is [0, 2, 4, 6]
  2. Evens(0) is empty and Evens(1) is [0]
  3. iter(e) returns the same object
  4. It is used up after one pass
  5. next works and ends with StopIteration
  6. The program prints [0, 2, 4, 6]

Stuck? One hint at a time

The solution unlocks after your first Check. Try first: that is where the learning happens.

main.py
Sign in to run your code.

Output

Press Run to see what your program prints.