Modules and the standard library

INPUT · Slides

Roll a die

01 / 07

When you want a different value each time

A die, a raffle, the order cards are dealt in. Some jobs have to come out differently every run.

The random module is what makes that happen. The code below picks one whole number from 1 to 6.

import randomprint(random.randint(1, 6))

Run it again and again and you get a 3, then a 6, then something else. It changes each time, which is exactly why no result can be printed here.

02 / 07

Fix the seed and the results line up

In this course, though, the marking needs the same output every time.

That is what random.seed is for. It fixes the seed that the randomness grows from, and the same seed always produces the same sequence.

This is a way of writing for when you need matching results, and nothing else. You would not write it in a real raffle or game, so keep that in mind.

import randomrandom.seed(0)print(random.randint(1, 6))

Result

4

03 / 07

randint includes both ends

random.randint(a, b) returns one whole number that is a or more and b or less.

The thing to watch is that b is included. range(1, 6) stopped at 5, but random.randint(1, 6) does give you 6. For a die, this is the one you want.

import randomrandom.seed(0)for i in range(3):    print(random.randint(1, 6))

Result

4
4
1

04 / 07

choice picks one out

To pick one item out of a list, use random.choice. It is the standard move for a raffle or a "suggestion of the day".

You hand it the list itself, and it does not matter how many items are in it.

import randomrandom.seed(0)fruits = ["apple", "orange", "grape"]print(random.choice(fruits))

Result

orange

05 / 07

shuffle rearranges the list itself

random.shuffle mixes up the order — think of shuffling a pack of cards.

There is one trap here. shuffle rewrites the list you gave it and returns nothing. Write colours = random.shuffle(colours) and you end up with None in colours.

import randomrandom.seed(0)colours = ["red", "blue", "yellow"]random.shuffle(colours)print(colours)

Result

['red', 'yellow', 'blue']

06 / 07

random gives a decimal from 0 up to 1

random.random(), with nothing in its brackets, returns a decimal that is 0 or more and under 1.

It looks useless at first glance, but it is handy for writing probabilities. random.random() < 0.3 is the condition "three times in ten".

import randomrandom.seed(0)print(random.random())

Result

0.8444218515250481

07 / 07

Being unpredictable is hard

Producing an unpredictable number is a genuinely hard problem. You are asking a machine that follows a fixed set of steps to hand you something that was not fixed.

Python has that hard part ready for you from the start. Whatever you want to do, somebody has probably already made it. Before you start inventing a raffle from first principles, think of random.