How to Generate Random Numbers in Python
Sometimes you will need to generate random numbers in Python. Fortunately, Python has a native package called
random, which can be used to generate numbers at random easily.
In this tutorial, we will learn how to use the
random Python package to get random boolean values and random numbers from different ranges of numbers.
Import the Package
The first step is to import the native
random Python package that will allow us to generate numbers easily.
Generate Random Boolean
We can generate random boolean values by using the
random.random() method. This method generates random floating-point numbers between
1. Finally to get a whole number, round the float to the nearest integer by using the
boolean = round(random.random()) print(boolean)
Generate Random Numbers in a Range
To get random integers from a range, use the
random.randint() method, passing the lowest possible number as the first argument and the highest as the second.
integer = random.randint(0,10) print(integer)
In the example above we are getting a random integer between
Generate a List of Random Numbers
To generate a list of random numbers from a range, create an empty
list followed by a
for loop that on each iteration will generate a random number before appending it to the
for i in range(0,10): integer = random.randint(10,20) numbers.append(integer) print(numbers)
[16, 12, 16, 17, 17, 15, 14, 13, 16, 18]
The sample() Method
We can generate a
list of random numbers in a cleaner way by using the
random.sample() method. The first argument is the range of random numbers to select from and the second is the number of samples to get.
number_list = random.sample(range(1, 100), 5) print(number_list)
[12, 68, 47, 92, 74]
You now know how to generate random numbers in several different ways in Python using the