daiyue daiyue - 1 month ago 7
Python Question

Python randint not equal to 0

I am trying to use

random.randint
to randomly generate a single
int
between a range, e.g.
randint(-2,2)
, however, it could possibly generate
0
, which is not expected, so I am wondering is there a way to make it not equal to
0
. Or just use a loop until
randint(-2,2)
not generate
0
, and get the output.

cheers

Answer

Don't use randint() then; it picks an integer from a continuous range of values, not a discrete set.

Use the random.choice() function instead, passing in a list of just those integers you want to pick from:

random.choice([-2, -1, 1, 2])

This'll return a random value from that list.