Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keeping the data of a variable between runs of code

Tags:

python

list

save

For a school project I am making a hangman game in Python. Right now my code picks a word from a dictionary like so:

WordList = ["cat", "hat", "jump", "house", "orange", "brick", "horse", "word"]
word = WordList[random.randint(0, len(WordList) - 1)]

right now the list of words has to be set within the code before running it, but I added the ability to add words to the list while running it:

if command == "add":
    while True:
        print("type a word to add to the dictionary")
        print("type /b to go back to game")
        add = raw_input("word: ")

        if add != "/b":
            WordList = WordList + [add]

            print add, "added!"
        else:
            print("returning to game")
            break

however, once I exit the code, the added words are obviously not saved, so I would either have to manually add all the words to the list, or add a bunch of words to the list once the code starts every time. so I am wondering if there is a simple way that I can have the variable save after the code is finished, so that WordList will keep the added words next time the code starts. the program I use to write python is Jetbrains PyCharm, if that makes a difference. Apologies for any un-optimal code, I'm new to code.

like image 921
Jancl0 Avatar asked Aug 08 '15 08:08

Jancl0


People also ask

What is stored in the variable?

Many variables store numbers and strings, like the ones above. Variables can also store other types of data, like lists, dictionaries, and Boolean values (true/false). We'll start by learning numbers and strings, and dive into advanced types later.

How does Python store data in variables?

Assigning Values to Variables Python variables do not need explicit declaration to reserve memory space. The declaration happens automatically when you assign a value to a variable. The equal sign (=) is used to assign values to variables.

What can a variable hold in Python?

Variable names may contain letters, digits (0-9) or the underscore character _ . Variable names must begin with a letter from A-Z or the underscore _ character. Either lowercase or uppercase letters are acceptable. Variable names may not be a reserved word in Python.

What is variable scope in Python?

A variable is only available from inside the region it is created. This is called scope.


1 Answers

Simply pickle the data you want to keep persistent. Since your use case doesn't require very complex data storage, pickling is a very good option. A small example:

import pickle

word_list = ["cat", "hat", "jump", "house", "orange", "brick", "horse", "word"]

# do your thing here, like
word_list.append("monty")

# open a pickle file
filename = 'mypickle.pk'

with open(filename, 'wb') as fi:
    # dump your data into the file
    pickle.dump(word_list, fi)

Later when you need to use it again, just load it up:

# load your data back to memory when you need it
with open(filename, 'rb') as fi:
    word_list = pickle.load(fi)

Ta-da! You have data persistence now. More reading here. A few important pointers:

  1. Notice the 'b' when I use open() to open a file. Pickles are commonly stored in a binary format, so you must open the file in a binary mode.
  2. I used the with context manager. This ensures that a file is safely closed once all my work with the file is done.
like image 179
Quirk Avatar answered Sep 28 '22 06:09

Quirk