Python Friday #66: Generate Random Numbers

Sometimes you need some random numbers for your application. Python offers a nice built-in random number generator with a lot of functionality to solve this problem.

This post is part of my journey to learn Python. You can find the other parts of this series here.

 

Attention: Do not use random for security purposes

Before we start a word of warning. The random module implements pseudo-random number generators that are great for some random data but are far too predictable to be useful for anything related to security / cryptography. If you need a random number generator for that purpose, take a look at the secrets module.

 

Generate random floats

To get a random number between 0 and 1 we can use the random() method from the module with the same name:

Whenever we call random() it gives us another random number.

 

Generate random integers

The random module offers many ways to get what you want. If you do not like one way you most often have a second approach. To get random integers between 0 and 10 you can use the functions randint() or randrange(). Let us first look at randint() that takes two arguments for the lower and upper boundary (the upper boundary is part of the range of possible random numbers):

The randrange() function has two arguments for the lower and upper boundary as well, but here the upper boundary is not part of the range of possible random numbers. Therefore, if we want to get numbers up to 10 back, we need to call the method with 11 as the upper boundary:

 

Get multiple random numbers at once

We can combine the random functions with list comprehension and get many numbers at once. This is not only useful when you need a list of random numbers, it helps you to spot the of by one error when you do not remember that the upper boundary of randrange() is not part of the possible numbers.

 

A bit less randomness

When it comes to testing, random numbers are not that great. Luckily for us, we can set the random number generator to a starting value that will then always produce the same random numbers. For that we can call the seed() function with a value. As long as you use the same value it does not matter what value it is:

If we run this code again (on a different command Prompt or in an IDE) we get the same output:

You can try this on your own computer, and it should give you the same output.

 

Next

The random module offers many more functions. Next week we look at ways to pick random elements from lists and how we can do that without accessing those elements through their position.

2 thoughts on “Python Friday #66: Generate Random Numbers”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.