teaching for loops before lists (was Re: Range Operation pre-PEP)

Alex Martelli aleaxit at yahoo.com
Thu May 10 04:48:04 EDT 2001


"Roman Suzi" <rnd at onego.ru> wrote in message
news:mailman.989472800.1598.python-list at python.org...
    ...
> > > Even recursion could be explained without lists in Python,
> > > why for-loops need this prerequisite?
> >
> > done much python training lately, or are you just making
>
> Yes. I taught programming classes a year ago.
> That is where I had some trouble with for-loops.

Personally, I've found that for-loops can easily
be taught without having introduced lists yet,
because they work on ANY sequence -- and a datatype
you will surely have introduced VERY early in any
Python course is "string"!  A string is a sequence.
This is of limited (though non-null) usefulness in
most Python use, but it SURE comes in handy when
teaching Python to a totally-raw beginner...:

"""
For example, let's print the vowels, only, from
the string the user has introduced.  This is easy
because we can look at any string one character
at a time with the for statement.

astring = raw_input("Please enter a string: ")
print "Vowels:",
nvowels = 0
for c in astring:
    if c in 'aeiouAEIOU':
        print c,
        nvowels = nvowels + 1
print
print nvowels,"vowels in total"
if nvowels:
    print "The last vowel was",c
"""

then you can go on to explain break, for/else,
and so on, all based on this simple toy example
about looping character by character on a string.

I do think one probably needs to have introduced
raw_input, strings, integers, assignment,
print, and if, before loops can fruitfully be
presented to a raw beginner.  But having some
nice special syntax for range literals would not
alter that, it seems to me.  Lists, if you wish,
can still come later, anyway.


Alex






More information about the Python-list mailing list