3

OK, teaching python to the kids. We just wrote our first little program:

b = 0
for a in range (1, 10)
    b = b + 1
    print a, b

Stops at 9, 9. They asked "why is that" and I can't say that I know the answer.

My code always involves files, and my "for row in reader" doesn't stop one line short, so I don't actually know. In mathematical notation, this behavior would be [1,10). Technically (1,10) would be 2,3,4,5,6,7,8,9, and indeed I want [1,10].

4

3 回答 3

7

It's just usually more useful than the alternatives.

  • range(10) returns exactly 10 items (if you want to repeat something 10 times)
  • range(10) returns exactly the indices in a list of 10 items
  • range(0, 5) + range(5, 10) == range(0, 10), which makes it easier to reason about ranges
于 2013-06-22T18:25:22.100 回答
3

This is just how python's range works. Quote from docs:

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).

于 2013-06-22T18:24:58.363 回答
3

The point is that range is defined as range(start,stop,step=1) http://docs.python.org/2/library/functions.html#range. The final element is always less than stop.

In practical terms, it is defined that way because the indices of a list of len n are numbered 0 to n-1.

A more theoretically satisfying answer is that it avoids the alternative, which is that the last element in the sequence would be the first integer which is greater than or equal to stop, which would frequently be unexpected. It also leads to the nice properties which Pavel Anossov lists, all of which would be compromised by a greater than or equal rule.

A point on style: It is more usual to write range (1, 10) without the space, because range is a function which returns a list (or in 3.x, a generator) of the items in the requested range. for loops in python always iterate sequentially over the elements of a datastructure or generator (in general, an iterable object).

于 2013-06-22T18:25:44.083 回答