Question

Sorry to ask a question which is probably very simple, but how do you get random.randint() to output a value that is between two numbers, eg. 0 and 10, but every 2 numbers.

For example to output only these values (0,2,4,6,8,10)

Was it helpful?

Solution

Use random.randrange():

random.randrange(0, 11, 2)

This produces a random value in the range [0, 11) (not including 11), with a step of 2. I used 11 as the upper bound to ensure 10 is included in the possible values.

Quoting the documentation:

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.

Demo:

>>> import random
>>> [random.randrange(0, 11, 2) for _ in range(20)]
[6, 8, 6, 0, 4, 4, 8, 4, 10, 10, 6, 8, 10, 6, 0, 10, 2, 10, 4, 2]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top