Sometimes when programming it's helpful to use random numbers. For example, we might want to:
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.
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.
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.
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.
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:
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
Another advantage of randrange
? It returns whole numbers, rather than decimals!
In the console below:
random
module