Q:

Generate random integers between 0 and 9 in Python

belongs to collection: Python basic programs

0

Following are the few explanatory illustrations using different python modules, on how to generate random integers? Consider the scenario of generating the random numbers between 0 and 9 (both inclusive).

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Using randrange

Syntax:

    random.randrange(stop)
    random.randrange(start, stop, step)

Code:

>>> import random
>>> for i in range(10):
...     print(random.randrange(10))
... 
2
2
2
0
8
8
5
6
6
3

Using randint

Syntax:

    random.randint(a,b)

Code:

>>> import random
>>> for i in range(10):
...     print(random.randint(0,10))
... 
1
6
7
5
8
9
6
2
3
9
>>>

Using secrets

By using this method, we can generate cryptographically strong random numbers.

>>> from secrets import randbelow
>>> for i in range(10):
...     print(randbelow(10))
... 
6
5
2
0
7
2
0
1
2
6
>>> 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Python basic programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Python | Find the factorial of a number using recu... >>
<< Python | Find factorial of a given number (2 diffe...