Create random numbers

How can I generate integer random numbers?

I can create random numbers with the random module in Python.

First import the module like this

# generate random numbers
# module to import
import random

Alternatively, you can import like this, so that you don’t have to use the name of the module before the name of the functions:

from random import randint

Now, we can use different functions from this module to generate random numbers. Let’s see the random functions for integers.

Functions for integers

random.randrange(stop)
This function will generate a random integer number from 0 to stop (any number)

from random import randrange

>>> randrange(100)
82
>>>
random.randrange(startstop[step])
With start, stop and step (optional arguments), you can say wich can be the littles number and the interval between the number of choice in the interval. For example randrange(10, 100, 20) will return a number among 10 30 50 70 90, starting from 10 and with an interval of 20 each.
>>> print([randrange(10,100,20) for x in range(3)])
[90, 70, 10]

The example above shows a for loop where the randrange function is used 3 times and, as you can see in the result, we have 3 numbers all with a ‘distance’ of 20 (the step chosen as third optional argument).

random.randint(ab)
This is like randrange, but hasn’t the step argument and must have always the start and stop parameter.
from random import randint

>>> for n in range(10):
...  randint(1,10)
...
4
6
9
9
8
3
9
4
10
6
>>>

 

Published by pythonprogramming

Started with basic on the spectrum, loved javascript in the 90ies and python in the 2000, now I am back with python, still making some javascript stuff when needed.