Python-list Digest, Vol 169, Issue 7

ROGER GRAYDON CHRISTMAN dvl at psu.edu
Thu Oct 5 08:37:26 EDT 2017


On Wed, Oct 4, 2017 22:42 Stefan Ram (ram at zedat.fu-berlin.de) wrote:
>
Steve D'Aprano <steve+python at pearwood.info> writes:
>>So, "bottom-up" in this case means: iterators should be
>>taught before for-loops.
>>Why? 
>
>  The syntax for is (from memory):
>
>for <variable> in <expression>: <suite>
>
>  . As an example, I might show:
>
>for i in range( 3 ): ...
>
>  . This raises the question:
>
>      "What is the value of ?range( 3 )??".
>
>  "Bottom up" means that the simple and constituent parts
>  are taught before the complex and compound parts. I.e.,
>  ?range( 3 )? is explained before ?for i in range( 3 ):?.
>
>


The easy answer here is to not use the range in the first for loop.

I introduce for with actual collections  (e.g. lists, strings, dictionaries)

It is very easy to figure out what  "for i in [2, 6,32, 7, 5]" means.

This is very easy to understand, and I teach it early, to avoid this common
error:

"if i == 2 or 6 or 32 or 7 or 5"

which plagues Python and C programmers alike (only Java complains about that
one)

You can even access the proper subscripts for a list without using range(),
if you are willing to use enumerate().  

So, by teaching the for loop without the range, not only do you get to postpone
the details of what range() does   (and can even point out -- hey, that's
exactly
the same numbers as enumerate listed!)   but you also get your students to
believe that there is a better way to access the elements of a list than
counting
down the subscripts.

I still see a lot of instructors and programmers who newly migrate to Python
that use counting a range() as their first choice in traversing a list.
Teaching the for loop without using range, I believe, is the best way 
to forestall that habit.

Oh, and it also steers people from this error I often see:
"for i in len(list)"

Roger Christman
Pennsylvania State University





More information about the Python-list mailing list