/  Technology   /  Generate random integers between 0 and 9 in python
Generate random integers between 0 and 9

Generate random integers between 0 and 9 in python

In this article, let’s learn the different ways of generating random integers for a specified range.

  • Using randrange
  • Using randint
  • Using secrets

 

1. Using randrange:

We import this function from the random module.

Syntax:

 random.randrange(start, stop, step)
  • start:  The generation starts from this number. The default value is 0.
  • stop: The generation of numbers ends at stop-1.
  • step: The default value is 1.

This function raises the ValueError if value of stop <= start and if the number is non- integer

Note: start and stop are optional parameters.

 

Example:

import random

for i in range(10):
     print(random.randrange(10))

output:

 

2. Using randint():

This is an in-built method from the random module. 

Syntax:

randint(start, end)

Note: The value of end is inclusive.

This function raises ValueError when float type values are passed as parameters and a TypeError is raised when parameters other than numeric values are passed as parameters.

 

Example:

import random

for i in range(10):
     print(random.randint(0, 9))

output:

 

3. Using randbelow():

The randbelow() is a built-in function from the secrets module. This module is used for generating random numbers for handling essential data, such as passwords, account authentication, security tokens, and related secrets which are cryptographically strong. This module is supported in Python versions 3.6 and above.

Syntax:

randbelow[0, end)

Note: The value of end is exclusive.

 

Example:

from secrets import randbelow

for _ in range(10):
     print(randbelow(10))

output:

 

Leave a comment