The worksheetDownload the PDF
Answers

F3.7 Random numbers

Strings, lists and records · GCSE · OCR J277 2.2.3, AQA 8525 3.2.9, Edexcel 1CP2 6.6.1 · about 12 min

BugBotLab

What this lesson is about

randint, choice and seeds: dice, random tunes and a robot that wanders.

Questions 5 marks in all

  1. [1 mark]Which values can random.randint(1, 6) give?

    1. A1, 2, 3, 4, 5 or 6
    2. B1 to 5
    3. C0 to 6
    4. DAny real number from 1 to 6
    Answer: A. randint includes both ends, unlike range.
  2. [1 mark]What does random.choice(["red", "green", "blue"]) give?

    1. AOne of the three colours, picked at random
    2. BAll three in a random order
    3. CThe number 3
    4. DAlways red
    Answer: A. choice picks one item from a list.
  3. [1 mark]What does setting random.seed(42) before generating numbers do?

    1. AMakes the same sequence of numbers come out every run
    2. BMakes the numbers more random
    3. CLimits numbers to 42
    4. DStops random numbers
    Answer: A. Computers make pseudo-random numbers with a formula; the same seed gives the same sequence, which helps testing.
  4. [1 mark]Write the AQA pseudo-code call for a random whole number from 1 to 10.

    Answer: RANDOM_INT(1, 10). AQA's RANDOM_INT includes both ends.
  5. [1 mark]A dice program counts 600 rolls. About how many sixes should it see?

    1. AAbout 100, but rarely exactly 100
    2. BExactly 100
    3. CAbout 600
    4. DAbout 6
    Answer: A. Each face has a 1 in 6 chance, so around 100, with some variation each run.

The task: dice drive

Roll a dice three times with random.randint(1, 6). For each roll, print roll: <n> and drive forward <n> * 5 cm. At the end print total: <cm> with the total distance, worked out from the rolls. This task fixes its random numbers, so you get the same rolls each run.

# the two lines every program starts with: the commands, then the robot
from bugbot import *
connect()

import random

total = 0

The hint students can ask for: Roll inside the loop, print the roll, then drive a distance worked out from it. Keep a running total as you go.

A solution

from bugbot import *
connect()
import random

total = 0
for i in range(3):
    roll = random.randint(1, 6)
    print("roll:", roll)
    forward(50, distance=roll * 5)
    total = total + roll * 5
print("total:", total)

Any program that meets the task's checks is marked correct in the simulator; this is one way, not the only way.