How can I generate random integers between 0 and 9 (inclusive) in Python?
For example, 0
, 1
, 2
, 3
, 4
I had better luck with this for Python 3.6
str_Key = ""
str_RandomKey = ""
for int_I in range(128):
str_Key = random.choice('0123456789')
str_RandomKey = str_RandomKey + str_Key
Just add characters like 'ABCD' and 'abcd' or '^!~=-><' to alter the character pool to pull from, change the range to alter the number of characters generated.
Generating random integers between 0 and 9.
import numpy
X = numpy.random.randint(0, 10, size=10)
print(X)
Output:
[4 8 0 4 9 6 9 9 0 7]
In case of continuous numbers randint or randrange are probably the best choices but if you have several distinct values in a sequence (i.e. a list
) you could also use choice:
>>> import random
>>> values = list(range(10))
>>> random.choice(values)
5
choice
also works for one item from a not-continuous sample:
>>> values = [1, 2, 3, 5, 7, 10]
>>> random.choice(values)
7
If you need it "cryptographically strong" there's also a secrets.choice in python 3.6 and newer:
>>> import secrets
>>> values = list(range(10))
>>> secrets.choice(values)
2
if you want to use numpy then use the following:
import numpy as np
print(np.random.randint(0,10))
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.
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.