In this lesson we study ho to generate a Python random number.
Random numbers in Python, i.e. pseudorandom numbers, are used by first importing the random module. Then we just put in the script: import random.
If you also try to type help (‘random’) in interactive mode, you will see the specifications of this module, with the functions you can use in your scripts.
After importing the module then we can use all methods to generate the random numbers.
Python random number – random()
The random method generates a random decimal number between 0 and 1.
random.random()
Consequently, numbers with a comma between 0 and 1 are generated.
Python random number – Importing module
In Python it is possible to call only some elements of a module, thus avoiding to call an entire module.
For example, we can import only the functions we need using the keyword from followed by the name of the module, the import and the name of the method you want to import.
Here is a possible example:
from random import random
print(random())
As you can see, in this way it is no longer necessary to indicate random.random(), as in the previous example, but just random() is enough.
It is also possible to import all methods in this way as well:
from random import *
print(random())
print(randint(1,10))
Thus it is possible to use all methods without repeating random every time, but using only the name.
Python random number – randint()
The randint() method generates a random integer in a range specified in parentheses.
random.randint(1, 10)
In this example, random numbers between 1 and 10 are generated.
Python random number – randrange()
The randrange() method generates a random integer, in a range of values such as randint, but the step can be specified.
For example:
random.randrange(1, 10, 2)
In this case, only the odd numbers from 1 to 10 can be generated, therefore: 1, 3, 5, 7, 9.
The step is however optional, in the sense that it can also be indicated only:
random.randrange(1, 10)
And in this case the integers from 1 to 10 can be generated.
So, to generate a Python random number we can use also randrange().
seed()
With this method you can initialize the random number generator.
So let’s take an example:
random.randint(1, 100)
If we run this script we will get a different random number each time.
If instead we first set the seed:
random.seed(10)
random.randint(1, 100)
You will always get the same random number, in this case 74. Now try to change the value of the seed.
Conclusion
These are just some of the random number methods in Python, in the next lesson I will introduce some other methods.
Useful links
Introduzione al linguaggio Python