Python | Modules | Random module

The random module allows you to generate random numbers but it also allows access to functions that support many operations. One of the functions it supports and we will be using here is randrange. We will see it in action in the following example:

import random

random_number = random.randrange(0,10)

while random_number != 4:
	random_number = random.randrange(0,10)

Now, first of all we don’t know how many times we are going to loop. The condition is to loop until the variable random_number is 4. You can see my result below.

Python random module

First, we import random module.
On the second line, a random number is assigned to the variable random_number using the function randrange() from the random module.

The third line starts the loop and prints random numbers on the screen as they are generated. When number 4 is generated the loop stops. Number 0 might be included in the generated numbers but number 10 will be excluded.

Leave a Reply