Python – Generate random integers between 0 and 9
Few Python examples to show you how to generate random integers between 0 (inclusive) and 9 (inclusive)
0 1 2 3 4 5 6 7 8 9
1. randrange
1.1 Generates random integers between 0 – 9
#!/usr/bin/python
import random
for i in range(10):
print(random.randrange(10)) # 0-9
Output
7
4
1
1
5
1
4
3
0
9
1.2 Generates random integers between 10 (inclusive) – 19 (inclusive)
#!/usr/bin/python
import random
for i in range(10):
print(random.randrange(10, 20)) # 10-19
Output
12
18
12
10
10
19
18
12
19
15
2. randint
Alias for randrange(start, stop+1)
#!/usr/bin/python
import random
for _ in range(10):
print(random.randint(0, 9)) # 0-9
Output
7
2
0
9
8
6
1
3
5
8
3. secrets
Generates cryptographically strong random numbers, read this module secrets
#!/usr/bin/python
from secrets import randbelow
for _ in range(10):
print(randbelow(10))
Output
9
0
4
9
3
6
2
7
4
5
References
About Author
Comments
Subscribe
0 Comments