Drop links or images here to add them to the editor.

In this topic students learn to generate random numbers and make random choices, using the random module.

Learning objectives and goals

Be able to read, comprehend, trace, adapt and create Python code that:

Slide deck

This chapter was written for Dodona from new material by the course author, after the rest of the course had been converted, so it has no deck of its own. The author’s Intermediate Python series has a Numbers deck that covers the random-numbers half of this chapter with different examples (it also covers data types, casting and modulo, both taught elsewhere in this course): on Google Slides. A PDF copy is kept on Dodona too.

Teacher notes

Random numbers are the first thing in this course that makes a program behave differently on two runs with the same input. That is what makes them motivating (dice, cards, guessing games) and also what makes them awkward to reason about: there is no single right output to predict. The predict and run activity handles this by asking for the set of possible outputs, the lowest, the highest and anything that can never appear, rather than a specific number.

The chapter introduces three tools, one per theory page. randint comes first because its two arguments read naturally as “lowest” and “highest”. choice follows because it builds directly on the previous chapter’s lists, and randrange comes last because it builds on range, including the step.

Key points

Errors and misconceptions

How the exercises are tested

Every exercise in this chapter uses random numbers, so the tests set a fixed seed before each student program runs: the same seed always gives the same sequence of random numbers, so the tests know the secret number or the hand of cards in advance, and feed in guesses chosen for it. This only works when the student’s program asks for random numbers the same way the model solution does, which is why each exercise description names the call to use and when to make it (once, after the mode is chosen; value before suit on every card). Calls that are equivalent for the same seed are accepted: randrange(1, 101) for randint(1, 100), and card_values[random.randint(0, 12)] for random.choice(card_values).

A student whose program works when they play it but fails the tests has usually made a random call in a different order or place from the one the description asks for. The descriptions explain seeding in a callout, and that is worth pointing to rather than debugging the game logic.