In Python, how does a for loop with `range` work?

前端 未结 6 1292
醉梦人生
醉梦人生 2021-01-03 19:20
for number in range(1,101): 
    print number

Can someone please explain to me why the above code prints 1-100? I understand that the range functio

6条回答
  •  清歌不尽
    2021-01-03 19:31

    This is a slightly confusing issue for new programmers in Python that have experience in object-oriented or procedural languages (c, Java etc.)

    The difference between those languages is that Python does not support a "counting"-like for iteration that is constantly used in C,Java etc :

    for(i = 0; i < 10; i++){
    ...
    }
    

    In contrast, Python implements only a for that is similar to the Iterator interface of object-oriented languages (Java programmers will be familiar with this) :

    for object in object_list
        ....
    

    So, in your example "range"[1,101] is the list (object_list) containing all numbers from 1 to 100 and "number" is the iterator (object) that takes the place of each one number

提交回复
热议问题