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

Remind them that there is a reason the range function works this way. One helpful property of it is that the number of times the loop will run is equal to the second argument of range minus the first argument.

I think people get really hung up on this, but the fact is for loops in Python are very different than from C. In C, for loops are basically a wrapper around a while loop.

These two examples should help show the difference between how loops work in C versus python.

# for(int x=1; x <= 10; x++)
x = 1
while x <= 10:
    print(x)
    x += 1


i = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]  # range(1, 11)
for x in i:
    print(i)

But honestly, the real problem here is that all loops and arrays are easier to understand and work with if they start at zero, not one. Please consider adjusting your examples to start at zero.

This way, if you want to loop 10 times, you use the number 10.

   # for(int x=0; x < 10; x++)
x = 0
while x < 10:
    print(x)
    x += 1


i = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]  # range(10)
for x in i:
    print(i)

Show them the two C++ variants:

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

# using < operator
for(int i = 1; i < 11; i++)
    { /* do something */ }

And tell them that python's range function operates like the second.


You could show them this code for a better understanding:

start = 1
length = 10
for i in range(start,start+length):
    print(i)

There is also another feature that works like this, it's called slice.


I believe there are two simple ways to answer the question. 1) One way to explain this answer is by using mathematical notation half closed interval [a,b). In this interval, one endpoint is included (In this example it is 'a' ) but not the other endpoint ('b'). So for your example,

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

(1,11) is a half closed interval where a and b are 1 and 11 respectively.

2) You can also explain using the following examples

    for i in range(1,11)  //in python 
        {do something}

    for(int i=1;i<11;i++)  //in C++
        {do something}

In both of these case, i iterates from 1 to 10. This seems more intuitive to me.

Tags:

Python

Loops