The "loop and a half"

Steve D'Aprano steve+python at pearwood.info
Wed Oct 4 11:26:10 EDT 2017


On Wed, 4 Oct 2017 09:35 pm, Stefan Ram wrote:

> Steve D'Aprano <steve+python at pearwood.info> writes:
>>For-each loops are MUCH easier to understand, and should be taught first.
> 
>   I prefer a bottom-up approach.

I prefer an effective approach that starts with the simplest concepts first,
not the most complex.

 
>   For loops are based on iterators.

That's an implementation detail that is not necessary to understand in order
to use for-loops. Python had for-loops for many years before it gained
iterators, and even today in Python 3 you can iterate over non-iterators.

py> class X:  # not an iterator!
...     def __getitem__(self, i):
...             if i < 3:
...                     return str(i)*2
...             raise IndexError
...
py> for obj in X():
...     print(obj)
...
00
11
22


X instances have no __iter__ or __next__ methods and are not iterators.



>   So, "bottom-up" in this case means: iterators should be
>   taught before for-loops.

Why? 

As an educator, you should care about teaching topics in whatever order makes
learning easier, not according to some theoretically pure order.

Do you really think that it is hard to teach a simple "do this three times"
example:

for i in range(3):
    print("do this")

example until you've covered iterators, exceptions, try...except
StopIteration, and while loops?


>   But iterators are too abstract to be taught very early.

I agree with that. So don't teach them. You don't need to care about the
implementation of iteration in order to teach iteration. Most beginners
probably won't write their own iterators for many years.



>   But I will teach iterators and for loops not much later than
>   while-loop.
> 
>   Maybe this way: Use a while-loop and try-catch to get values
>   from an iterator until exhausted, and then introduce the
>   for-loop as an abbreviation for that.

Ah, I get it now... this is a cunning plan to make Python seem like a
confusing, difficult language, so your students will learn Javascript
instead.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list