Home » Python » Python programs

Generate random integers between 0 and 9 in Python

Here, we are going to learn how to generate random integers between 0 and 9 in Python programming language?
Submitted by Sapna Deraje Radhakrishna, on November 28, 2019

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).

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
>>> 






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.




Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.