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.
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:
Later when you need to use it again, just load it up:
Ta-da! You have data persistence now. More reading here. A few important pointers:
'b'
when I useopen()
to open a file. I like to use pickle files as binaries. This helps avoid problems with some complex object structures when you pickle them.with
command. This ensures that a file is safely closed once all my work with the file is done. This helps prevent my pickles being accidentally accessed or overwritten.You have to use persistent storage: write the words in a file when you add them and retrieve them from this file when the program starts.
If you exit the code you stop the process. For this reason you lose all data. You have to add the words keeping the script alive. The suggestion is to use a server that processing all your calls (example: http://flask.pocoo.org/) or to use the python command input (https://en.wikibooks.org/wiki/Python_Programming/Input_and_Output).
But remember... if you stop the process you lose all data, it is normal.
Otherwise, before stopping your script, you have to save all the data into a file or database and load them when the script starts.