On 29Jun2017 13:57, Irv Kalb <i...@furrypants.com> wrote:
Now I am looking at the change in the range function. I completely understand
the differences between, and the reasons for, how range works differently in
Python 2 vs Python 3. The problem that I've run into has to do with how to
explain what range does in Python 3. In Python 2, I easily demonstrated the
range function using a simple print statement:
print range(0, 10)
I discussed how range returns a list. I gave many examples of different values
being passed into range, and printing the resulting lists.
[... and the teaching path from there ...]
But Python 3's version of the range function has been turned into a generator.
Again, I understand why this happened, and I agree that this is a good change.
The problem is, how can I explain this concept to students who are just
learning lists, function and function calls, etc. The concept of how a
generator works would be extremely difficult for them to get. The best
approach I have seen so far has been to build a simple for loop where I print
out the results, like this:
for someVariable in range(0, 10):
print(someVariable)
[...]
How feasible is it to try a functional approach (in the "functional
programming" sense)?
They already have lists I understand. Explain that a list is a concrete
explicit expression of a sequence of values. Then that there are other ways to
express a sequence of values (and allude that there are many ways to express
various things).
So that when one speaks the prose "the values from A to B", that implies the
values A, A+1, etc up (to B-1 in python). In many cases it doesn't matter wther
you actaully compute them unless you need a specific value.
So "range(A, B)" is a Python builtin expressing the prose "the values from A to
B". It doesn't compute them until you need the specific values. This makes it
small (no huge list of things for a huge range) and fast (no need to actually
count out all the values).
Then show them that you can still use it in iteration situations, with the for
loop being the classic example.
As a bonus, later you can use this paradigm when talking about generators and
classes that implement "large but only computed on demand" things.
Cheers,
Cameron Simpson <c...@zip.com.au>
--
https://mail.python.org/mailman/listinfo/python-list