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
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
Try This,
Try:
More info: https://docs.python.org/3/library/random.html#random.randint
You can try this:
Notes:
More information on numpy.random.uniform
More information on numpy.ndarray.astype
The original question implies generating multiple random integers.
Many responses however only show how to get one random number, e.g.
random.randint
andrandom.choice
.Multiple Random Integers
For clarity, you can still generate multiple random numbers using those techniques by simply iterating
N
times:Sample of Random Integers
Some posts demonstrate how to natively generate multiple random integers.1 Here are some options that address the implied question:
random.sample
returnsk
unique selections from a population (without replacement):2In Python 3.6,
random.choices
returnsk
selections from a population (with replacement):See also this related post using
numpy.random.choice
.1Namely @John Lawrence Aspden, @S T Mohammed, @SiddTheKid, @user14372, @zangw, et al.
2@prashanth mentions this module showing one integer.
The
secrets
module is new in Python 3.6. This is better than therandom
module for cryptography or security uses.To randomly print an integer in the inclusive range 0-9:
For details, see PEP 506.
From the documentation page for the random module:
random.SystemRandom, which was introduced in Python 2.4, is considered cryptographically secure. It is still available in Python 3.7.1.
Instead of
string.digits
,range
could be used per some of the other answers along perhaps with a comprehension. Mix and match according to your needs.