So basically im new to python and programming in general. I was wondering say you have a situation where you have a dictionary and are asking the user if they want to add or delete terms in the dictionary. So I know how to add or delete the term in dictionaries but how do “save” that data for the next time the program starts. Basically, if the user added a word to the dictionary and then I asked them if they wanted to return to the main menu using a while loop, how would you make it so the word they added is now permanently in the dictionary when he returns to the menu and starts the program over?
Here is what I had. Mind you I’m a beginner and so if it looks weird, then sorry…lol….nothing serious:
loop=None
while True:
#The initial dictionary
things={"house":"a place where you live",
"computer":"you use to do lots of stuff",
"iPod":"mp3 player",
"TV":"watch shows on it",
"bed":"where you sleep",
"wii":"a game system",
"pizza":"food"}
#Menu
print("""
Welcome to the Dictionary of Things
Choose your preference:
0-Quit
1-Look up a Term
2-Add a Term
3-Redefine a Term
4-Delete a Term
""")
choice=input("\nWhat do you want to do?: ")
elif choice=="2": #Adds a term for the user
term=input("What term do you want to add? ")
if term not in things:
definition=input("Whats the definition? ")
things[term]=definition #adds the term to the dictionary
print(term,"has been added to the dictionary")
menu=input("""
Would you like to go back to the menu?
Yes(Y) or No(N): """)
if menu=="Y":
loop=None ----->#Ok so if they want to go back to the menu the program should remember what they added
elif menu=="N":
break
Update:
Your problem is that you redefine the dictionary at the start of each loop. Move the start definition of the dictionary to before the While loop, and you are in business.
Dictionaries and lists are mutable objects. Hence, if it is modified in a function, it stays modified where it was called too:
If you now run main_function, it will print out a dictionary that includes ‘c’.