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