Modules and handling errors
Import library code with random and os, keep the program alive on bad input with try/except, then ship the full RPG.
What You'll Learn
- Import and use modules like random and os
- Pull a single function in with from ... import
- Keep the program alive on bad input with try/except
- Combine every system into a complete RPG
In this lesson:
- Import ready-made code with modules (
randomfor chance,osfor the file system) - Pull a single function in with
from ... import - Keep the program alive on bad input with
try/exceptinstead of crashing - Ship the complete Python Kingdom RPG, every system from three lessons in one file
Last lesson your save/load system worked, but it was fragile. Load a missing file and it dies. Let a player type "three" instead of 3 and it dies too. This lesson has both fixes.
First you'll borrow ready-made code with modules: random for anything that should feel unpredictable, os for checking the file system safely. Then you'll catch bad input with try/except. By the end, every system from these three lessons converges into one complete RPG that you ship.
Modules: random and os
A module is a bundle of ready-made code you load with import. You don't write it, you borrow it. Python ships with dozens of them, and at the hackathon you'll lean on two: random for anything that should feel unpredictable, and os for touching the file system safely.
The random module
A game with no randomness is a game you've already beaten. random is what makes a battle land differently each time:
Run it twice and you get different numbers. That's the whole point. Three functions cover almost everything you'll need:
random.randint(a, b)gives a whole number betweenaandb, both included. Damage rolls, dice, loot drops.random.choice(list)picks one item from a list at random. A random enemy, a random room, a random reward.random.shuffle(list)rearranges a list in place. Shuffling a deck, randomising question order.
Python ships these for free, so this is your first taste of random.choice() and friends. Now you know where they come from.
The os module
os lets your program talk to the operating system: check if a file exists, make a folder, list what's in a directory. The one function you'll use constantly is os.path.exists():
[!WARNING] Throwaway filesystem each run The playground filesystem is temporary. Folders you create with
os.makedirs()and files you write disappear when you reload the page, andos.listdir(".")shows the playground's own files, not your computer's. The code is correct, it just runs in a fresh, throwaway filesystem each time.
This matters for save games. If you try to load a file that isn't there, the program crashes. Check first with os.path.exists(), and if there's no save, start a new game instead of dying.
Importing just one function
Typing random.randint every time gets old. With from ... import you pull a single name straight into your file and drop the prefix:
Use the plain import random when you want a few functions from a module, and from random import randint when you only need one and you're calling it a lot.
Handling errors with try/except
Back in the input lesson, you turned text into a number with int(), and you saw what happens when the player types "three" instead of 3: Python throws a ValueError and the whole program dies. Now it's time to handle it. Here it is.
The tool is try/except. You put the risky line in a try block, and Python tries to run it. If it crashes, instead of killing the program, Python jumps to the except block and runs your backup plan:
Result:
That is not a number. Defaulting to 0 potions.
Potions to buy: 0
Read it like a sentence: "try to convert the text; if that raises a ValueError, fall back to zero." The program keeps running. The player gets a clear message instead of a wall of red error text.
This is the difference between a toy and a program someone else can use. At the hackathon, the judges will type weird things into your menus. With try/except around your int() calls and your file reads, a bad input becomes a gentle "try again" instead of a crash mid-demo.
Dictionaries store data in key-value pairs, perfect for structured information like a creature's stats. Files let you save and load data, just like a save game. Always use with open() for safety, wrap risky conversions in try/except, and the random and os modules extend what your programs can do.
Exercise : Random encounters
Exercise : Check the save before loading
Complete game code: Python Kingdom (FINAL)
Congratulations! This is the complete Python Kingdom game with ALL systems: character creation, battle, inventory, shop, dungeon, puzzle room, save/load, and the final boss fight!
[!WARNING] Save lives only until reload This game reads your input and saves to a file. In the playground,
input()pops up a prompt box, and the save file lives only until you reload the page. Run it the same way on your own computer and the save would stick around.
Bonus: Simple graphics with text
Optional deep-dive. Skip this if you just want the basics; it's a fun extra, not required to finish the game.
You can draw simple graphics right in the console using text characters. Here are two examples you can add to your game: an HP bar and a mini-map.
HP bar - a bar that shrinks as the hero loses health:
Mini-map - shows dungeon rooms as boxes:
Run each example to see the graphics printed right here in the console.
You shipped a game. Now what?
That's the fundamentals done. Take a second to notice what you just pulled off: a full RPG with character creation, battles, a shop, a dungeon, a save system, and a final boss. Every piece is something you learned one lesson at a time.
Here's the thing nobody tells beginners. Those same pieces (a dictionary of data, a loop that reads input, a file that remembers state) are the skeleton of almost every small project people build at a hackathon. You didn't learn a pile of toy lessons. You learned the toolkit.
So the next chapter changes the question. Instead of "how does Python work," it's "I've got a weekend and a team, what do I build?" That's a different kind of problem, and it's the fun one. See you there.
Test Your Knowledge
Check how well you understood the lesson with these 2 questions.

