~ Randomness


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