GRADE 8 · COMPUTING · UNIT 1 · LESSON 1.37

Computational thinking and programming

Generate random choices within bounds

Read a little. Try the workbook. Check your answers. Choose one section below to get started.

Topic 1.37 · Generate random choices within bounds14 fillable worksheet pagesRead at your own pace

LET’S TRACE, REASON AND TEST

Generate random choices within bounds

A random choice still has a defined domain. Read whether the API returns an integer or a real value and which bounds are included. One observed value cannot establish the full range.

Today’s two goals
  • Model selection with replacement and use inclusive randint bounds to select program behaviour.
  • Explain my method and support it with a labelled trace, example or test record.
Original PaxaKids illustration for Generate random choices within bounds. Use the supplied program and data models for precise workbook facts.
An original PaxaKids workbook scene. Use the supplied programs and data for precise workbook facts.

Work through an example

Python random.randint(2, 5) can return the integers 2, 3, 4 or 5, including both endpoints. It should not return 1, 6 or a fractional value.

Try before your workbook

Could random.randint(4, 7) return 7? Could it return 4.5?

Explore the clues

Tap one card to find out more.

Understand the idea

A random choice still has a defined domain. Read whether the API returns an integer or a real value and which bounds are included. One observed value cannot establish the full range.

Concept to practise: Generate random choices within bounds.

Work through an example

Python random.randint(2, 5) can return the integers 2, 3, 4 or 5, including both endpoints. It should not return 1, 6 or a fractional value.

Try before your workbook

Could random.randint(4, 7) return 7? Could it return 4.5?

Check my readiness thinking

It may return 7 because the upper endpoint is included. It does not return 4.5 because randint chooses integers.

Your original programs and learning models

These original PaxaKids program and data models support your workbook. Some examples deliberately contain faults to investigate. Follow their headings and preserve exact code case, punctuation and order. Traces and supplied records are not claims of physical testing.

Use a generated number to choose behaviour

A program can generate a number and use selection to choose an action, message or game outcome. Python’s random module uses pseudo-random generation. A normal run may produce any allowed value; repeats are possible.

Predict the set of possible results from the bounds, rather than promising one next result. For testing, a controlled value can help check each branch separately from the generator.

Prepare six numbered action slips

Make six same-size paper slips numbered 1–6, fold them alike and put them in a container. Mix without choosing a visible number. This complete original mapping gives each slip a different classroom action. An individual can trace a stated sample sequence if a practical round is not performed.
Prepare six numbered action slips — original model
Slip numberAssigned action
1Draw a small circle
2Point to a blue object
3Write the word robot
4Show a thumbs-up sign
5Say one shape name
6Count backward from three

Follow a draw-with-replacement model

Use the procedure in order. Returning the slip keeps all six options available for each new draw. Equal chances depend on comparable slips, folding and mixing; a small set of draws need not have equal counts.
  1. Mix the six similarly folded slips.
  2. Draw one slip and read its number.
  3. Perform or describe its mapped action.
  4. Refold and replace it before mixing again.

Read inclusive randint bounds

random.randint(a, b) returns an integer from a through b, including both endpoints. Supply integer bounds with a no greater than b. This rule is documented in the Python random guide. Fill the smallest and largest possible results.
Read inclusive randint bounds — original model
Function callSmallestLargest
random.randint(2, 6){'clue': 'Integer', 'prompt': 'Lower bound random.randint(2, 6)', 'answers': ['2']}{'clue': 'Integer', 'prompt': 'Upper bound random.randint(2, 6)', 'answers': ['6']}
random.randint(0, 4){'clue': 'Integer', 'prompt': 'Lower bound random.randint(0, 4)', 'answers': ['0']}{'clue': 'Integer', 'prompt': 'Upper bound random.randint(0, 4)', 'answers': ['4']}
random.randint(-3, 1){'clue': 'Integer', 'prompt': 'Lower bound random.randint(-3, 1)', 'answers': ['-3']}{'clue': 'Integer', 'prompt': 'Upper bound random.randint(-3, 1)', 'answers': ['1']}
random.randint(7, 7){'clue': 'Integer', 'prompt': 'Lower bound random.randint(7, 7)', 'answers': ['7']}{'clue': 'Integer', 'prompt': 'Upper bound random.randint(7, 7)', 'answers': ['7']}

Import, call, store and output a random integer

This complete original example imports the module, calls randint with two bounds, stores its returned integer in choice and prints it. Its exact next choice is not given in advance.
Original Paxa bounded choice
import random
choice = random.randint(2, 6)
print("Choice:", choice)

Read a complete original guessing program

The target is generated from 2 through 6. Enter a valid integer guess. The program prints Match for equality; otherwise it reveals the generated target. It reads one guess, rather than looping until successful.
Original Paxa one-guess program
import random
target = random.randint(2, 6)
guess = int(input())
if target == guess:
    print("Match")
else:
    print("Target:", target)

Use controlled targets to check high/low feedback

This complete test version reads a target first, then a guess. It deliberately uses controlled input instead of a random target, so each branch can be checked reliably. The packaged random version replaces only the target input with randint(2, 6).
Original Paxa deterministic feedback test
target = int(input())
guess = int(input())
if guess == target:
    print("Match")
elif guess < target:
    print("Too low")
else:
    print("Too high")

Trace equal, lower and higher guesses

Use page 7. Each row supplies target then guess. Write the exact final message. Check the comparison from the guess to the target, not in the reverse direction.
Trace equal, lower and higher guesses — original model
TargetGuessFeedback
43{'clue': 'Exact message', 'prompt': 'Feedback target4 guess3', 'answers': ['Too low']}
44{'clue': 'Exact message', 'prompt': 'Feedback target4 guess4', 'answers': ['Match']}
45{'clue': 'Exact message', 'prompt': 'Feedback target4 guess5', 'answers': ['Too high']}
26{'clue': 'Exact message', 'prompt': 'Feedback target2 guess6', 'answers': ['Too high']}

Select one of four original jokes

This complete original example generates a choice from 1–4 and prints one corresponding joke. The final else handles choice 4 because the generator’s documented bounds and the preceding conditions cover the other three values.
Original Paxa random joke selector
import random
choice = random.randint(1, 4)
if choice == 1:
    print("Why did the bookmark rest? It lost its place.")
elif choice == 2:
    print("Why did the robot pack glue? To stick to its plan.")
elif choice == 3:
    print("Why did the pencil pause? It needed a point.")
else:
    print("Why did the clock read a map? To find the right time.")

Predict a joke branch from a controlled choice

Use page 9 with each stated choice for testing. Write only the object that appears in the selected joke: bookmark, robot, pencil or clock. Full output messages belong in the practical test record.
Predict a joke branch from a controlled choice — original model
Controlled choiceObject in selected joke
1{'clue': 'Object name', 'prompt': 'Joke object for choice1', 'answers': ['bookmark']}
2{'clue': 'Object name', 'prompt': 'Joke object for choice2', 'answers': ['robot']}
3{'clue': 'Object name', 'prompt': 'Joke object for choice3', 'answers': ['pencil']}
4{'clue': 'Object name', 'prompt': 'Joke object for choice4', 'answers': ['clock']}

Read the original curriculum station picker

This full original C06 program separates test mode from random mode. Test mode reads a station number, making each function branch reproducible. Random mode generates one from 1–4. A function returns the selected message to the caller for printing.
Original curriculum C06 station picker
import random
def station_message(number):
    if number == 1:
        return "Sketch a robot"
    elif number == 2:
        return "Invent a puzzle"
    elif number == 3:
        return "Trace an algorithm"
    elif number == 4:
        return "Explain a test"
    return "Unknown station"
print("Enter test or random. In test mode, enter a station number next.")
mode = input().strip().lower()
if mode == "test":
    choice = int(input())
    print("Station:", choice)
    print(station_message(choice))
elif mode == "random":
    choice = random.randint(1, 4)
    print("Station:", choice)
    print(station_message(choice))
else:
    print("Mode must be test or random.")

Predict the station picker’s final message

For the first five rows use mode test, then enter the station value. The last row uses an unknown mode and reads no station. Write only the final message; test mode also prints Station: followed by the chosen number.
Predict the station picker’s final message — original model
ModeStation inputFinal message
test1{'clue': 'Exact message', 'prompt': 'Station final message test 1', 'answers': ['Sketch a robot']}
test2{'clue': 'Exact message', 'prompt': 'Station final message test 2', 'answers': ['Invent a puzzle']}
test3{'clue': 'Exact message', 'prompt': 'Station final message test 3', 'answers': ['Trace an algorithm']}
test4{'clue': 'Exact message', 'prompt': 'Station final message test 4', 'answers': ['Explain a test']}
test0{'clue': 'Exact message', 'prompt': 'Station final message test 0', 'answers': ['Unknown station']}
othernot read{'clue': 'Exact message', 'prompt': 'Station final message other None', 'answers': ['Mode must be test or random.']}

Files for this activity

Use these original PaxaKids practice files with the matching workbook. Work on a local copy in the appropriate editor. Some examples deliberately contain faults to investigate; a downloaded file is not a completed practical test.

Paxa the Fox

Try one step with Paxa!

Trace code in the stated order and preserve exact spelling and case. Use fictional data. Label a prediction, paper trace, simulator run and physical-device test separately; an unperformed test stays Pending. Save personal responses before leaving.

Our Unit 1 learning path
  1. Lesson 1.1: Recall algorithms and representations
  2. Lesson 1.2: Purpose and conventions of pseudocode
  3. Lesson 1.3: Input, output and strings
  4. Lesson 1.4: Identifiers and assignment
  5. Lesson 1.5: Arithmetic and translation
  6. Lesson 1.6: Trace and review a sequence
  7. Lesson 1.7: Conditions and two-way flow
  8. Lesson 1.8: IF THEN and indentation
  9. Lesson 1.9: IF THEN ELSE and decision diagrams
  10. Lesson 1.10: Ordered ELSEIF and fallback ELSE
  11. Lesson 1.11: Match flowchart and pseudocode branches
  12. Lesson 1.12: AND, OR and NOT
  13. Lesson 1.13: Grouping, precedence and review
  14. Lesson 1.14: Why software searches
  15. Lesson 1.15: A successful linear search
  16. Lesson 1.16: An unsuccessful search and termination
  17. Lesson 1.17: Practise and communicate the search
  18. Lesson 1.18: Translate conditions into Python
  19. Lesson 1.19: One-branch IF programs
  20. Lesson 1.20: Two-way IF ELSE programs
  21. Lesson 1.21: Ordered ELIF choices
  22. Lesson 1.22: Ranges and independent decisions
  23. Lesson 1.23: Boolean operators in Python
  24. Lesson 1.24: Design and test recommendations
  25. Lesson 1.25: Trace, debug and reflect
  26. Lesson 1.26: Choose data types and recognise Boolean literals
  27. Lesson 1.27: Set and use Boolean flags
  28. Lesson 1.28: Explain and identify constants
  29. Lesson 1.29: Express constants in three algorithm forms
  30. Lesson 1.30: Use a fixed factor in a calculation
  31. Lesson 1.31: Cast to Boolean and validate an empty response
  32. Lesson 1.32: Recall calls and trace return values
  33. Lesson 1.33: Supply parameters and reuse library code
  34. Lesson 1.34: Choose and import libraries responsibly
  35. Lesson 1.35: Round with floor and ceiling
  36. Lesson 1.36: Use pi and investigate another mathematical feature
  37. Lesson 1.37: Generate random choices within bounds
  38. Lesson 1.38: Investigate random real values and review library use
  39. Lesson 1.39: Retrieve test tables and predict selection outcomes
  40. Lesson 1.40: Decompose everyday problems
  41. Lesson 1.41: Decompose programs and organise shared work
  42. Lesson 1.42: Develop through repeated build/test cycles
  43. Lesson 1.43: Predict and verify algorithm outcomes
  44. Lesson 1.44: Choose representative and boundary tests
  45. Lesson 1.45: Build, execute and review a test plan
  46. Lesson 1.46: Recall physical inputs and compare transmission media
  47. Lesson 1.47: Configure a radio group and agree a message scheme
  48. Lesson 1.48: Send and receive numbers and strings
  49. Lesson 1.49: Trace numeric message sequences
  50. Lesson 1.50: Transmit text and use received data in conditions
  51. Lesson 1.51: Diagnose and extend a message protocol
  52. Lesson 1.52: Review communication and evidence of testing
  53. Lesson 1.53: Project 1: Adventure story
  54. Lesson 1.54: Project 2: Fire, Water, Earth
  55. Lesson 1.55: Check your progress 1
For grown-ups: using this lesson

Your answers are checked in your browser. Open responses need grown-up review and are shown separately from the automatic score. Check your work, then use “Retry answers to practise” to revisit mistakes while keeping correct responses.

Read one explanation, discuss the model and try the readiness check before the workbook. Choose “Mark lesson finished” when ready. Optional account progress saves lesson position and completion across devices; save personal responses before leaving.

2. Fill in your workbook

Read the teaching and complete workbook instructions. Choose, write or draw; Answer list offers larger controls. Trace code precisely and distinguish predictions from actual tests. Review designs, explanations and drawings with a grown-up.

Generate random choices within bounds14 student pages · original artwork

Opening your PDF…

Swipe sideways across the worksheet on a small screen, or use “Answer list” for larger controls.

TAKE YOUR PRACTICE OFFLINE

3. Download the student worksheet

All 14 original A4 student pages, ready for pencil-and-paper practice. Choose Review Answers to check your work on this webpage.

Student worksheet only · PDF · 8.5 MiB · No answer key included

Download worksheet PDF ↓

TRY FIRST, THEN CHECK TOGETHER

Download the student worksheet →

4. Answers & guidance

Finished your try? Open the guide and compare one worksheet at a time. Your own words may be different and still explain the right idea.

Shown on this webpage only. There is no answer-key download, and this guide is left out when printing the page.

Show answers for all 14 worksheets

Worksheet 1

  1. Question 1: What can a generated number control in these examples? which action or message a program selects
  2. Question 2: Can two consecutive independent choices repeat the same allowed number? yes, repeats are possible

Worksheet 2

  1. Question 3: Which action is selected by slip 3? Write the word robot

Worksheet 3

  1. Question 4: Which step allows the same number to appear again next time? replacing the drawn slip
  2. Question 5: Would the sample sequence 2, 2, 6 fit this model? yes, because each slip is replaced

Worksheet 4

  1. Question 6: Lower bound random.randint(2, 6) 2
  2. Question 7: Upper bound random.randint(2, 6) 6
  3. Question 8: Lower bound random.randint(0, 4) 0
  4. Question 9: Upper bound random.randint(0, 4) 4
  5. Question 10: Lower bound random.randint(-3, 1) -3
  6. Question 11: Upper bound random.randint(-3, 1) 1
  7. Question 12: Lower bound random.randint(7, 7) 7
  8. Question 13: Upper bound random.randint(7, 7) 7

Worksheet 5

  1. Question 14: What is the smallest possible choice? 2
  2. Question 15: What is the largest possible choice? 6
  3. Question 16: How many distinct integers can this call return? 5
  4. Question 17: Which is a valid prediction before a normal run? the output amount is one of 2, 3, 4, 5 and 6

Worksheet 6

  1. Question 18: Which variable stores the generated number? target
  2. Question 19: Which function from the module generates that value? random.randint / random.randint()
  3. Question 20: List all possible target integers, smallest first. 2, 3, 4, 5, 6 / 2,3,4,5,6

Worksheet 7

  1. Question 21: If the guess is below the target, which feedback is correct? Too low
  2. Question 22: Why use a stated target for a branch test? the expected comparison and message are reproducible

Worksheet 8

  1. Question 23: Feedback target4 guess3 Too low
  2. Question 24: Feedback target4 guess4 Match
  3. Question 25: Feedback target4 guess5 Too high
  4. Question 26: Feedback target2 guess6 Too high

Worksheet 9

  1. Question 27: What is the upper bound supplied to randint here? 4
  2. Question 28: Why should a changed range be reviewed with the branches? new values may reach the fallback without a distinct intended joke

Worksheet 10

  1. Question 29: Joke object for choice1 bookmark
  2. Question 30: Joke object for choice2 robot
  3. Question 31: Joke object for choice3 pencil
  4. Question 32: Joke object for choice4 clock

Worksheet 11

This page introduces the activity. There are no marked responses on this sheet.

Worksheet 12

  1. Question 33: Station final message test 1 Sketch a robot
  2. Question 34: Station final message test 2 Invent a puzzle
  3. Question 35: Station final message test 3 Trace an algorithm
  4. Question 36: Station final message test 4 Explain a test
  5. Question 37: Station final message test 0 Unknown station
  6. Question 38: Station final message other None Mode must be test or random.

Worksheet 13

  1. Question 39: Create or use the six page 2 action slips and mapping. Carry out a short draw-and-replace round with actual records, or trace the provided sequence 2, 2, 6 and mark the practical round Pending. Explain replacement and why equal chances do not imply equal short-run counts. Then investigate page 6: identify import, module, function, integer bounds and target value’s use. Increase its upper bound to 9 and add the page 7 high/low logic. Test equality, low and high guesses with controlled targets, then record actual random runs or Pending. Keep full code, predictions, observations and corrections. Six distinct mapped slips, similar fold/mix, action and replacement before next draw; repeated 2 then 6 possible. Actual round/roles or honest provided simulation with Pending; no equal-frequency guarantee. import random, module random, randint integer lower 2/upper 6 inclusive, target int compared with guess. Changed upper 9 gives integers 2–9 inclusive; complete high/low selection uses equality then guess<target Too low, else Too high. Controlled branch tests and random observations clearly distinguished, exact outputs and full source with corrections/retests. No numeric learner score or invented paired/physical execution. Grown-up review; personal evidence is required.

Worksheet 14

  1. Question 40: Create or adapt a program that generates an integer from 1–4 and prints a different appropriate original joke for each value. Keep a mapping table and test every branch with a stated controlled choice before any normal random runs. Explain inclusive bounds and how the returned integer controls selection. Compare this with the original page 11 station picker: test stations 1–4, an unknown station and an unknown mode, recording full predictions and actual output or Pending. Identify the returned message and caller’s print, keep sources and records, and state one improvement. Four appropriate distinct jokes and complete mapping for randint(1,4), all inclusive outcomes covered without numeric grading. Original page9 example acceptable as support if adaptation and own contribution explained. Controlled branch1–4 tests separate from random observations. Station test1/2/3/4 -> Sketch a robot/Invent a puzzle/Trace an algorithm/Explain a test, with initial instruction and Station: n; test0 -> Unknown station; unknown mode -> Mode must be test or random. Function returns text and caller prints it. Full source/mapping/tests actual or Pending, corrections/retest and next step, no invented learner GUI or partner performance. Grown-up review; personal evidence is required.
Back to my workbook ↑

Curriculum & workbook reference

Computing for your homeschool day

Explore Generate random choices within bounds with this free Grade 8 Computing lesson. Read one idea together, try the fillable workbook and return to review at your own pace. Download the same student worksheet PDF for pencil-and-paper practice.

Fit learning around your family’s day. There is no timer and no sign-up is needed to use the lesson. An optional account saves your lesson position and completion across devices. Workbook responses and drawings stay in this tab; save a copy of your responses before leaving.

Understand your results

Closed answers are checked in your browser. Drawings and written explanations need grown-up review and are shown separately from the automatic score. Check your work, then use “Retry answers to practise” to revisit mistakes while keeping correct responses.

Choose Review Answers after trying the activity. The guide stays on the webpage; the worksheet download contains only the student pages.

For programme background, visit the Cambridge Lower Secondary Computing overview. PaxaKids provides independent original companion practice.

Book page references identify the related teaching topic. File-management and responsible-data preparation are original PaxaKids material; orientation or contents pages are not presented as teaching citations for those skills. The explanations, characters, programs and exercises here are original PaxaKids companion practice. Practical tasks require the appropriate editor and, where applicable, suitable equipment. A design or paper trace is not a verified hardware result. Only completed, reviewed lessons are listed.

Explore the Cambridge Lower Secondary Computing curriculum for programme background. PaxaKids is an independent learning resource.