/  Technology   /  Generate random integers between 0 and 9

Generate random integers between 0 and 9

Generate random integers between 0 and 9

 

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.

 

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.

 

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.

 

Leave a comment