Teaching the "range" function in Python 3
Chris Angelico
rosuav at gmail.com
Thu Jun 29 17:21:53 EDT 2017
On Fri, Jun 30, 2017 at 6:57 AM, Irv Kalb <Irv at furrypants.com> wrote:
> I am wondering if other teachers have run into this. Is this a real problem? If so, is there any other way of explaining the concept without getting into the underlying details of how a generator works? Do you think it would be helpful to use the words "sequence of numbers" rather than talking about a list here - or would that be even more confusing to students?
>
The easiest way is to use the word "collection" for things you iterate
over (rather than the concrete term "list"). So you can loop through
(or iterate over) a collection of explicitly given numbers:
for number in [12, 93, -45.5, 90]:
or you can loop through a range of numbers:
for number in range(10):
or you can loop through any number of other things:
for file in os.scandir("."):
They're all collections. I'd also use this as a great opportunity to
talk about naming conventions - a collection is named in the plural
("things") whereas individual items are named in the singular
("thing") - which means that it's very common to have a loop that
looks like this:
for thing in things:
for file in files:
for num in numbers:
for key in keyring:
That rule should help people keep things straight, without being
bothered by the difference between lists, ranges, and dictionary
views.
ChrisA
More information about the Python-list
mailing list