Python: why does `random.randint(a, b)` return a range inclusive of `b`?

后端 未结 4 1612
再見小時候
再見小時候 2020-12-05 04:06

It has always seemed strange to me that random.randint(a, b) would return an integer in the range [a, b], instead of [a, b-1] like

4条回答
  •  执笔经年
    2020-12-05 04:45

    I guess random.randint was just the first attempt at implementing this feature. It seems that the Python developers also felt that this was a problem, which is why in v1.5.2 they added another method randrange with more standard parameters:

    random.randrange([start], stop[, step])
    

    Return a randomly selected element from range(start, stop, step). This is equivalent to choice(range(start, stop, step)), but doesn’t actually build a range object.

    You can use randrange instead of randint to avoid surprising people.

    On the other hand, in many situations where the problem is phrased as 'choose a random number between 1 and 6' it might be more natural to use randint(1, 6) instead of writing randrange(1, 7) or randrange(min, max + 1).

提交回复
热议问题