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
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
random.randrange(-39,-9)will give you back a random number between
Another advantage of
randrange? It returns whole numbers, rather than decimals!
In the console below: