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

前端 未结 6 1273
醉梦人生
醉梦人生 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:50

    Python 2.7 documentation states:

    range([start], stop[, step])¶

    This is a versatile function to create lists containing arithmetic progressions. It is most often used in for loops. The arguments must be plain integers. If the step argument is omitted, it defaults to 1. If the start argument is omitted, it defaults to 0. The full form returns a list of plain integers [start, start + step, start + 2 * step, ...]. If step is positive, the last element is the largest start + i * step less than stop; if step is negative, the last element is the smallest start + i * step greater than stop. step must not be zero (or else ValueError is raised)

    EDIT: You may also want to look at xrange. EDIT: So basically:

    for ( start ; stop ; step )
    range( start, stop, step ) // where start and step are optional
    

提交回复
热议问题