Friday, 17 May 2019

How to make a for-loop more understandable in python?

I am currently teaching some python programming to some fairly young students. One thing I want them to learn is how to write a for-loop.

So far, the way I have shown it to the students is like this:

for i in range(1,11):
    print(i)

which gives a loop where i goes from 1 to 10.

My problem is that it seems strange to students that they need to write 11 as the second argument to range(1,11) when they want the loop to go up to 10. The students find this confusing.

In C/C++ and related languages, such a loop can be written like this:

for(int i = 1; i <= 10; i++)
    { /* do something */ }

It seems to me like the C++ way of expressing the loop is more intuitive since in that case I can explicitly write 1 and 10 which are the first and last values that I want the loop variable to take.

When working with for-loops in python, I end up telling the students something like "we just have to accept that we need to write 11 when we want the loop to go to 10, it is a bit annoying but you just have to learn that the range function works in that way". I am not happy about that; I want them to learn that programming is fun and I am afraid this kind of thing makes it less fun.

Since python is often described as a language emphasizing readability, I suspect there is a nicer way to express a for-loop, a way that would cause less confusion for my students.

Is there a better and/or less confusing way to express this kind of for-loop in the python language?



from How to make a for-loop more understandable in python?

No comments:

Post a Comment