Dark theme

One of the things we've had to deal with is what happens if we do something to leave the game. It's hard to construct nested if statements so that these all work properly. It would be better if we could just jump out of the game at some point.

To do this, we'll use a library - sometimes called a module in Python. Libraries are code other people have written that we can use. They are written in chunks called functions. We've seen two functions already: print() and input(). Functions always end in parentheses, which we can use to pass information into the function - for example, what to put on the screen. Some functions also return stuff to us which we can attach to variables - for example, input returns to us what the user has typed.

These functions are part of a library built into Python, but most libraries you have to import. Let's look at how to do this.

At the very top of your program, put the following code:

import sys

Once you've done this, you can use the "sys" system library. One function in the sys library stops the program running: "exit()". We can add the following code to any location where we'd like the user to leave the game:

sys.exit()

Let's look at an example of where this might be useful...

[Home > Part 2 > Next]