The module named random can be used to generate random numbers in Python. To use a module you need to type import module. This loads all of the functions inside the module.
Keep in mind that random numbers with the random module are pseudo-random numbers. For most programs this is fine.
Related course: Complete Python Programming Course & Exercises
Random
The random module
To create random numbers with Python code you can use the random module. To use it, simply type:1
import random
This module has several functions, the most important one is just named random(). The random() function generates a floating point number between 0 and 1, [0.0, 1.0].
The random module has pseudo-random number generators, this means they are not truly random.
Generate random numbers
This example creates several random numbers.
Type the program shown below and run it:1
2
3
4
5
6
7
8
9
10import random
# Create a random floating point number and print it.
print(random.random())
# pick a random whole number between 0 and 10.
print(random.randrange(0,10))
# pick a random floating point number between 0 and 10.
print(random.uniform(0,10))
In all of the cases we use the random module. Several random numbers are generated.
If you want a random float between 1 and 10 you can use this trick:
1 | import random |
For random integers either case them to integers or use the randrange function.
If you are a beginner, then I highly recommend this book.
Study drill
Try the exercises below
- Make a program that creates a random number and stores it into x.
- Make a program that prints 3 random numbers.
- Create a program that generates 100 random numbers and find the frequency of each number.
After completing these continue with the next exercise.