We continue with our examples of handling random numbers. In this case we are going to see how easy it is to generate random even numbers with Python.
The first thing we have to know is that we are going to rely on the random library and specifically on the randrange() function. So the first thing will be to import said function from the library using an import statement within our code Python.
from random import randrange
Now that we have imported the randrange() function we must know how to use it. Since this has three parameters:
- start, the initial number of the sequence of possible randoms.
- stop, the final number of the sequence of possible randoms.
- step will be the variation of the numbers chosen within the range and is essential when generating even numbers.
In this way, if we want to generate even random numbers with Python from 0 to 100 we will write the following:
print randrange(0,100,2)
In the event that we want a sequence of even numbers, for example, 5 even numbers, we will have to use a for:
loop
for x in range(0,5):
print randrange(0,100,2)
We see that the for loop has been supported by the range() function to be able to manage the 5 iterations.
In this simple way we will have managed to generate random even numbers with Python.
