Final Project Guide: Program State

by Elliott Hauser

17 Nov 2022

State

We’ve talked a little bit about state, but now that we have users interacting with our programs, it’s important to return to this.

State refers to things that your program knows that change over time. So far, without users, it’s been important to understand so that we can avoid bugs. And many of you have found that printing variables is a helpful way to inspect state.

Now, in addition to yourself, you have the user to think about. Your program is going to have state, some of which you need to understand but can stay hidden to the user, and some of which needs to be displayed to the user.

The simplest way to store state is as a string or number in a variable. But, as your program grows, you’ll need to keep track of more things. You might then want to use a more complex data structure, like a dict, to store state. This is part of refactoring, or rewiring your program to be easier to rewrite, easier to understand, and/or more efficient.

Dict Review

Make a dict

mydict = { }
mydict = dict()
mydict = { "key" : "value" }

Get a value

mydict["key"]
# returns "value"

A dict of dicts has inner dicts as the values within an outer dict.

# set "key" value equal to empty dict from the start
mydict = { "key" : {} }

# OR if dict already exists set "key" equal to empty dict this way:
mydict["key"] = {}

# put a value in the inner dict
mydict["key"]["inner key"] = "inner value"

A dict of dicts might be a great data structure if you have a number of things that you want to collect specific pieces of data about.

  • data analysis: Let’s say you have a list of all the locations of various chain restaurants. You could create a dict with each chain as a key, and each key would point to a dict of information about that restaurant chain. You would want to end up with a dict something like this:
restaurants = {
    "Torchy's" : {
        "number_of_locations" : X,
        "states" : ["a list of states goes here"],
        ....
    }
    "Cookout" : {
        "number_of_locations" : Y,
        ....
    }
}

You could then access the statistics you’ve gathered from any chain in the dataset by calling

restaurants["Torchy's]["number_of_locations"]

Since the inner dicts are all the same, the pattern for getting the information is the same, letting you replace the name of the restaurant with a variable, or perhaps something the user entered in the text.

  • Turtle: you might use a dictionary to keep track of things like player lives left, the ‘mode’ the game is in, the number and location of hidden ‘treasures’ on the screen, and so on.
Elliott Hauser is an Assistant Professor at the UT Austin iSchool. He's hacking education as one of the cofounders of Trinket.io. Find Elliott Hauser on Twitter, Github, and on the web.