Random Numbers with Python

Random numbers are very important in computing. Whenever you need to simulate something in the real world where the outcome is unknown, random numbers come into play. A classic example is their use in games where you may want to simulate the throw of a die, for example.

Some of the applications of random numbers in computing are listed below.

  • Games
  • Gambling
  • Simulations
  • Cryptography
  • Statistical sampling
  • Machine Learning
  • Recaptcha for human verification on websites

It is interesting to note that random numbers are often not truly random, in the sense that if you know the starting point and you know the algorithm being used you can predict the next number in the sequence. However for many practical purposes this “pseudo-randomness” is perfectly adequate.

Python Random Integers

In Python, we work with random numbers using the random module, which we import using import random. There are many tools available in the module, but for now we will just focus on random.randint(). The . syntax here means “the randint() method of the random module.” random.randint(arg1, arg2) generates a random integer (whole number) between the first and second arguments, inclusive.

Run the code below in your favourite Python editor.

import random

# Print a random integer between 1 and 10 inclusive.
print(random.randint(1, 10))

# Let's do it a few times to check it's working as expected.
for i in range(10):
    print(random.randint(1, 10), end=",")  # end="," keeps the output on the same line, with commas between.

Sample output:

5
10,1,4,5,9,1,6,6,8,2,
  • See if you can understand why you get the output that you do
  • Try some different ranges for the arguments to random.randint()

Random sampling with Python

We can use list comprehension to generate a list of random integers like so:

import random

# Create a list of random integers between 1 and 100, inclusive.
data = [random.randint(1, 100) for _ in range(20)]

print(data)

Note the use of _ for the range variable. Since we don’t explicitly use it, we don’t need to name it.

Sample output:

[61, 41, 39, 42, 83, 50, 76, 89, 59, 63, 72, 10, 63, 59, 51, 22, 64, 34, 10, 12]

Now that we have some data, we can sample from it like so:

print(random.sample(data, 3))

The arguments here are the data to sample from, and the size of the sample. Note that with this method, you will not get duplicate samples.

Sample output:

[96, 43, 59]

There is a lot more you can do with random numbers is Python, but the two methods of the random module covered here, random.randint() and random.sample() are a great start, and I recommend that you play and experiment with them until you are confident with how they work. Then perhaps you can use them in your own programs.

Happy computing!

Sharing is caring!

Leave a Reply

Your email address will not be published. Required fields are marked *