Generate random integers between 0 and 9
Solution 1
Try:
from random import randrange
print(randrange(10))
Docs: https://docs.python.org/3/library/random.html#random.randrange
Solution 2
import random
print(random.randint(0,9))
random.randint(a, b)
Return a random integer N such that a <= N <= b.
Docs: https://docs.python.org/3.1/library/random.html#random.randint
Solution 3
Try this:
from random import randrange, uniform
# randrange gives you an integral value
irand = randrange(0, 10)
# uniform gives you a floating-point value
frand = uniform(0, 10)
Solution 4
from random import randint
x = [randint(0, 9) for p in range(0, 10)]
This generates 10 pseudorandom integers in range 0 to 9 inclusive.
Solution 5
The secrets
module is new in Python 3.6. This is better than the random
module for cryptography or security uses.
To randomly print an integer in the inclusive range 0-9:
from secrets import randbelow
print(randbelow(10))
For details, see PEP 506.
Note that it really depends on the use case. With the random
module you can set a random seed, useful for pseudorandom but reproducible results, and this is not possible with the secrets
module.
random
module is also faster (tested on Python 3.9):
>>> timeit.timeit("random.randrange(10)", setup="import random")
0.4920286529999771
>>> timeit.timeit("secrets.randbelow(10)", setup="import secrets")
2.0670733770000425
aneuryzm
Updated on August 05, 2022Comments
-
aneuryzm almost 2 years
How can I generate random integers between 0 and 9 (inclusive) in Python?
For example,
0
,1
,2
,3
,4
,5
,6
,7
,8
,9