I teach beginners programming (from 12-15 years old), and one of the options we made (because it was natural in Python) was to teach the concept of "repeat action" before the concept of variables.
We took off in Python using
for loop in range(10):
not to mention variable arrays and in C ++ with
#define repeat(nb) for(int _loop = 0 ; _loop < (nb) ; _loop++)
The idea was to hide the complexity of the classic cycle in order to insist on a “re-entry” part. We do not hide from students the fact that "repeat (10)" is not part of C ++, it is just a way to simplify learning.
At Pascal, we cannot do more than
for loop := 1 to 10 do
but this is normal because it is not so difficult to remember.
I was looking for something like this in Java, and I found that:
import java.util.List; import java.util.AbstractList; class Range { public static List<Integer> size(final int end) { return new AbstractList<Integer>() { @Override public Integer get(int index) { return 0 + index; } @Override public int size() { return end; } }; }; } public class Main { public static void main(String[] argv) { for (int loop : Range.size(10)) { System.out.println("xx"); } } }
for (int loop : Range.size(10))
still easier to remember than
for(int loop = 0 ; loop < 10 ; loop++)
but there are two problems:
- two variables are needed for transcoded loops: I don't think we can do much with this
- We have warnings because the
loop variable is not used
Do you see the best solution that we have?
Once again, we only want to provide some “tool” at the initial stage so that students can “repeat” actions before they know anything about the “variables”. We are not hiding from them, which are not in the language, and after several exercises (~ 80-100) we ask them to use the real syntax.
<h / "> We have about 20 exercises before introducing variables: some of them relate to printing texts, but basically we provide one library with objects that you can manipulate (therefore, variables are hidden in the state of the object). For example, you can think of a “turtle lottery.” Thus, the concept of “loop” can be manipulated and “seen” before entering explicit variables, and you can perform interesting exercises very quickly.
For example, in Python, where you want to visit each case of a 10x10 table once and only once, and then return to the starting point (lower left corner):
from robot import * top() for loop in range(4): for loop in range(8): top() right() for loop in range(8): bottom() right() for loop in range(8): top() right() for loop in range(9): bottom() for loop in range(9): left()
This exercise is not so simple, but the syntax is really simple and allows the student to focus on the "algorithmic" part, and not on the "langage" part. After a few exercises, students begin to communicate, and we can introduce more syntactic and more complex concepts, such as variables.