How To: Randomness


Random numbers

Sometimes when programming it's helpful to use random numbers. For example, we might want to:

  • simulate a dice roll
  • choose letters at random
  • pick a random number between 0 and 100

Python provides a set of built-in tools, through the random module, that help find random-ish numbers. We'll check them out in the next section.

Random-ish numbers?

What's "random-ish" mean? Well, these numbers aren't truly random; computers are so deterministic that they can't actually act randomly, so we simply ask them to behave as close to random as possible.

We ask them to do this with a bunch of math; if you're curious for how this works, the Wikipedia article about the Mersenne Twister is a good place to start.

Getting random numbers

To start, type import random, which will import the random module. This is the way you import, or add, Python's pre-made random tools into your project.

If you didn't import these tools, you'd have to make them yourself, and trust me: it's much more fun to use random numbers than to come up with them.

Random numbers between 0 and 1

To get your first random number, type random.random():

Try typing it a few more times. This'll give you back different numbers between 0 and 1 - at random.

Random numbers between any two numbers

If you'd like to get a random number from another range – say, between 0 and 10 – you'll have to transform what random.random() gives back.

To get a random number between 0 and 100, we'll have to multiply random.random() by 100:

For a random number between 50 and 100, we'll have to multiply random.random() by 50 and then add 50:

Random whole numbers between any two numbers

If you thought that transforming random.random() numbers with addition and multiplication was a bit tedious, you're right – and there's an easier way!

There's another random tool, called randrange (short for "random range") that will return random numbers from a specific set of numbers:

  • random.randrange(4,100) will give you back a random number between 4 and 100
  • random.randrange(-39,-9) will give you back a random number between -39 and -9
  • ... and on and on, so long as you put the smaller number before the larger number in the parentheses:

Another advantage of randrange? It returns whole numbers, rather than decimals!

Challenge

In the console below:

  • import the random module
  • find a few random numbers between 5 and 25
  • find another random number between 100 and 200