Deviopath › Python

Countdown Iterator

Medium · Iterators

A for loop works with any object that follows the iterator protocol: __iter__() returns the iterator (often self), and __next__() returns the next value or raises StopIteration when there are no more. An iterator is used up after one pass: looping over it again gives nothing.

Write a class Countdown(start) that produces start, start - 1, ..., 1 and then stops. If start is 0 or negative, it produces nothing. __iter__ must return self.

The driver run_countdown is already written: it loops over the same object twice and checks that iter(countdown) is countdown.

Next: Count Calls with a Decorator