Week 7 of 8
Lists and Randomness
Programs become unpredictable. Students store several values in a list and use random.choice() to pick one at random, so the program does something different every run. They build a short adventure game whose path and prize change each time - and meet import for the first time, because now they need it.
- Estimated time
- 60 minutes
- Project
- Random Adventure Game
The idea
A list holds many values in one variable, written inside square brackets. random.choice() reaches into a list and pulls out one item at random, so the program can surprise the player. To use random you first bring it in with import random at the top - the first time you have needed a tool that is not built in. Lists plus randomness are what make a game feel different every time you play.
What you will learn
- Make a list and read items from it.
- Use random.choice() to pick a random item from a list.
- Explain why import random has to come first.
- Fix a program that uses random without importing it.
New words
- list
- An ordered collection of values inside square brackets, like ["a", "b", "c"].
- item
- One value stored in a list.
- import
- Brings in extra tools Python does not load by default, like the random module.
- random.choice()
- Picks one item from a list at random.
Project: Random Adventure Game
Edit the starter code below and press Run to see it work. Use Reset starter code to go back to the original at any time.
Run your program to see the output.
Expected output
You head down a quiet cave.
At the end, you find an old map.Mini challenge
Add a third list of characters the player meets along the way, pick one at random, and print a line about them.
Debugging challenge
Python says random is not defined. This program uses random.choice(), but random is a tool that has to be brought in first. What single line belongs at the very top?
Broken code
paths = ["a dark forest", "a quiet cave"]
path = random.choice(paths)
print(path)Show solutionHide solution
Bring in the random tool at the top:
import randomExtension challenge
Ask the player's name with input() at the start, then use it in the random story so the adventure feels like it is about them.
Reflect
Two players run this and get different stories. Why does that make a game more fun to play more than once?
Teacher notes
Because the output is random, the expected output is just one example - runs will differ, and that is the point. Reinforce that import goes at the top. Lists are indexed from 0, but random.choice() means students do not need indexing yet; keep the focus on picking from a list.
Facilitating this lesson? See the teacher & librarian guide for how to run it, common mistakes, and an offline backup activity.
Finished this lesson? Mark it complete to unlock the next week.