[Python-ideas] Simpler syntax for basic iterations

Andre Roberge andre.roberge at gmail.com
Fri Oct 9 23:51:23 CEST 2015


On Fri, Oct 9, 2015 at 6:27 PM, Erik <python at lucidity.plus.com> wrote:

> On 09/10/15 21:27, Ryan Gonzalez wrote:
>
>> Just use:
>>
>> for _ in range(n):
>>      # magic here
>>
>> and tell them they'll figure out what the _ is later on. That's how I
>> learned it...
>>
>
> Or, to make it look that little bit more "natural", spell it:
>
> for each in range(n):
>   # magic
>
> ... and then one day, move on to explain that "each" is actually something
> you can USE rather than just being a fixed part of the syntax - at which
> point it can be spelled better according to what it actually is.
>
> An alternative suggestion to remove the need for the variable (rather than
> a new keyword) would be something like allowing the "var in" part to be
> optioinal:
>
> for <iterator>:
>   # magic
>
> ... but the problem with that is that pretty much the ONLY use would be
> for this sort of "iterate n times" construct or something where you're
> relying on the iterator to have side-effects (which is pretty nasty):
>
> foo = myiter()
> for foo:
>   bar(foo.getcurrentvalue())
>
> It seems like a lot of effort just to hide a bit of syntax for a very
> specific use-case when you can just temporarily make that syntax look a bit
> nicer for your audience.


I have been using a special builtin alternative (which can be translated
into various human languages, as Reeborg's World is meant to support
various languages) as

def repeat(f, n):
    for i in range(n):
        f()

and used as

repeat(turn_left, 3)

as seen here: http://reeborg.ca/docs/begin_py_en/repeat.html
(and for the French version: http://reeborg.ca/docs/begin_py_fr/repeat.html
).

In smaller tutorials, I sometimes use the standard "for .." construct
instead of this repeat() function, but it always feels clumsy for beginners.

However, repeat()  has its own complexity in that it uses function
arguments, which are inexistant in the original Karel the Robot approach
and do not need to be used for simple worlds in Reeborg's World.

And, just to put things in perspective: I first wrote RUR-PLE in 2004 and
have been working on tutorials for it, discussing with many teachers using
it during all these years.  So, yes, I know I (and others) can make do
without this special construct I am suggesting ... but at the cost of a
larger hurdle for the students than would be required if the alternative
construct existed.

André




>
>
> E.
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20151009/f32c7911/attachment.html>


More information about the Python-ideas mailing list