[Python-ideas] Simpler syntax for basic iterations

Terry Reedy tjreedy at udel.edu
Sat Oct 10 04:30:18 CEST 2015


On 10/9/2015 4:22 PM, Andre Roberge wrote:
> Summary:  Visual environments based on using
> simple functions without using variables have been found
> to be useful to introduce programming concepts to young
> learners.  While Python is an ideal language for beginners,
> the Python construct for iterations, namely
>
> for var in range(n):
>      # block
>      # of
>      # code
>
> does require a variable and is needlessly complicated for
> beginners.  A simpler construct like:
>
> repeat n:    # n is a specific integer
>      # block
>      # of
>      # code
>
> would be useful to have in such contexts.  Other keywords could
> be chosen instead of "repeat" used above.

...

> do n:
>      # block
>      # of
>      # code indented like Python
>
> To do something equivalent in Python requires to use:
>
> for var in range(n):
>      # block
>      # of
>      # code

...

> An alternative would be to reuse the "for" keyword by
> adding this new construct to the grammar:
>
> for n:
>      # block
>      # of
>      # code

It was once proposed that int n should be an abbreviation for range(n), 
at least in the context of a for statement, partly on the basis that 
counts can be defined in set theory as the set of previous counts, or a 
similar variation, but really for convenience.  Guido vetoed the idea.
---

I think trying to persuade core developers to mutilate Python a bit, at 
couple of years in the future, is futile.  And unneeded.  Instead, 
translate, say 'repeat n:' into 'for _ in range(n):' with something like

def robotrans(codetext):
     out = []
     for i, line in enumerate(codetext.splitlines()):
         if line.startswith('repeat'):
             <check rest of line and either append translation
              or raise SyntaxError with proper details>
         else:
             out.append(line)
     return '\n'.join(outlines)

You could, for instance, patch IDLE two places (for shell and editor 
code) to run robotran on user code before compiling.  You could also add 
'repeat' to the list of keywords for colorizing.  I would be willing to 
help (without any guarantee of code stability).

Guido recently approved on idle-dev that we rethink IDLE for beginners. 
  I have already thought about adding the necessary hooks so that 
education developers like you could define beginner Python dialects, 
such as you suggest here.  This would open a world of possibilities, 
such as 'move 3' versus 'move(3)', and foreign language keywords.  I 
just started a thread 'Running beginner Pythons'.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list