I'm writing an adventure game, and I'm writing functions in different files, such as the saveGame function and read function. There are 4 main files, all interconnected. The main one is agMain.py. My issue is that I've imported one of my other files agRead.py, and call the function within that called read(). Here is the data for the agRead.py:
import os
import operator
import sys
import agSave
import agCreation
def read():
while True:
try:
file = open("agData.txt", "r")
except:
exec(open("agCreation.py").read())
break
break
file = open("agData.txt", "r")
data = file.readlines(0)
encrypFName = data[0]
encrypSName = data[1]
encrypAge = data[2]
encrypGender = data[3]
encrypHealth = data[4]
encrypMaxHealth = data[5]
encrypArmour = data[6]
encrypMaxArmour = data[7]
encrypHealthPotions = data[8]
encrypExp = data[9]
encrypMaxExp = data[10]
encrypLevel = data[11]
encrypGold = data[12]
encrypMaxGold = data[13]
encrypPowerLevel = data[14]
encrypMaxPowerExp = data[15]
encrypPowerExp = data[16]
encrypStage = data[17]
fName = encrypFName.strip()
sName = encrypSName.strip()
age = encrypAge.strip()
gender = encrypGender.strip()
health = encrypHealth.strip()
maxHealth = encrypMaxHealth.strip()
armour = encrypArmour.strip()
maxArmour = encrypArmour.strip()
healthPotions = encrypHealthPotions.strip()
exp = encrypExp.strip()
maxExp = encrypMaxExp.strip()
level = encrypLevel.strip()
gold = encrypGold.strip()
maxGold = encrypMaxGold.strip()
powerLevel = encrypPowerLevel.strip()
maxPowerExp = encrypMaxPowerExp.strip()
powerExp = encrypPowerExp.strip()
stage = encrypStage.strip()
As you can see, it sets variables such as stage and level. My agMain files however:
import os
import operator
import sys
import agSave
import agRead
while True:
agRead.read()
if (stage == 1):
exec(open("agStage1.py").read())
elif (stage == 2):
exec(open("agStage2.py").read())
elif (stage == 3):
exec(open("agStage3.py").read())
elif (stage == 4):
exec(open("agStage4.py").read())
elif (stage == 5):
exec(open("agStage5.py").read())
elif (stage == 6):
exec(open("agStage6.py").read())
elif (stage == 7):
exec(open("agStage7.py").read())
elif (stage == 8):
exec(open("ageStage8.py").read())
elif (stage == 9):
exec(open("agStage9.py").read())
elif (stage == 10):
exec(open("agStage10.py").read())
elif (stage > 10):
for i in range(100):
print("Game over!")
print("****************")
print("Well done, you have completed the game!")
exit()
else:
print("An error has occured.")
continue
As you can see here, it uses the stage when it from the function in the code. But it can't. If I run this, it says stage is not defined, like I hadn't run the function. Is it possible to set variables in a function, use the function, and use the variables in creates in a different file?
EDIT
At the time I made this, I had no knowledge of classes, so I apologise. Everyone who is having a similar problem (sharing variables between functions) just make a class with the functions you want as methods. It saves a lot of hassle!
https://docs.python.org/3/tutorial/controlflow.html#defining-functions:
More precisely, all variable assignments in a function store the value in the local symbol table; whereas variable references first look in the local symbol table, then in the local symbol tables of enclosing functions, then in the global symbol table, and finally in the table of built-in names. Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they may be referenced.
Assigning to a variable in a function implicitly creates a local variable in that function, unless you've declared it as global.
By using chaining, you can reduce the number of lines used and increase readability.
class Conf(object):
pass
def read():
while True:
try:
file = open("agData.txt", "r")
except:
exec(open("agCreation.py").read())
break
break
file = open("agData.txt", "r")
data = file.readlines(0)
conf = Conf()
conf.fName = data[0].strip()
conf.sName = data[1].strip()
conf.age = data[2].strip()
conf.gender = data[3].strip()
conf.health = data[4].strip()
conf.maxHealth = data[5].strip()
conf.armour = data[6].strip()
conf.maxArmour = data[7].strip()
conf.healthPotions = data[8].strip()
conf.exp = data[9].strip()
conf.maxExp = data[10].strip()
conf.level = data[11].strip()
conf.gold = data[12].strip()
conf.maxGold = data[13].strip()
conf.powerLevel = data[14].strip()
conf.maxPowerExp =data[15].strip()
conf.powerExp = data[16].strip()
conf.stage = data[17].strip()
return conf
You need to understand a little more about scoping. Inside a function, names that are bound by an assignment statement are created in the local namespace of the function call. This namespace is created when the function call is made and initialised with the values of the parameters bound to their names. When the function returns (or raises an exception) the namespace is deleted, and the names are no longer available.
Since you want to read lots of different values, consider creating an instance of a class. Instances also have a namespace, and names bound in that namespace will continue to be available until deleted or until the object is garbage collected.
After #Merlin published his helpful answer I decided to update this answer to include a data-driven version, reproduced below (but not tested). Thinking about this might lead you to a function that can create/initialise several different types of object.
Since execution speed is unlikely to be an issue I preferred an approach that was more generalised.
class Conf(object):
pass
def read():
while True:
try:
file = open("agData.txt", "r")
except:
exec(open("agCreation.py").read())
break
break
file = open("agData.txt", "r")
conf = Conf()
names = ["fName", "sName", "age", "gender", "health", "maxHealth",
"armour", "maxArmour", "healthPotions", "exp", "maxExp",
"level", "gold", "maxGold", "powerLevel", "maxPowerExp",
"powerExp", "stage"]
for name in names:
setattr(conf, name, next(file).strip()
return conf
The variables are only visible from inside read.
Contain the variables you want to use by doing something like this.
agRead.py
class Conf(object):
pass
def read():
while True:
try:
file = open("agData.txt", "r")
except:
exec(open("agCreation.py").read())
break
break
file = open("agData.txt", "r")
data = file.readlines(0)
encrypFName = data[0]
encrypSName = data[1]
encrypAge = data[2]
encrypGender = data[3]
encrypHealth = data[4]
encrypMaxHealth = data[5]
encrypArmour = data[6]
encrypMaxArmour = data[7]
encrypHealthPotions = data[8]
encrypExp = data[9]
encrypMaxExp = data[10]
encrypLevel = data[11]
encrypGold = data[12]
encrypMaxGold = data[13]
encrypPowerLevel = data[14]
encrypMaxPowerExp = data[15]
encrypPowerExp = data[16]
encrypStage = data[17]
conf = Conf()
conf.fName = encrypFName.strip()
conf.sName = encrypSName.strip()
conf.age = encrypAge.strip()
conf.gender = encrypGender.strip()
conf.health = encrypHealth.strip()
conf.maxHealth = encrypMaxHealth.strip()
conf.armour = encrypArmour.strip()
conf.maxArmour = encrypArmour.strip()
conf.healthPotions = encrypHealthPotions.strip()
conf.exp = encrypExp.strip()
conf.maxExp = encrypMaxExp.strip()
conf.level = encrypLevel.strip()
conf.gold = encrypGold.strip()
conf.maxGold = encrypMaxGold.strip()
conf.powerLevel = encrypPowerLevel.strip()
conf.maxPowerExp = encrypMaxPowerExp.strip()
conf.powerExp = encrypPowerExp.strip()
conf.stage = encrypStage.strip()
return conf
and agMain.py
import agRead
while True:
conf = agRead.read()
if conf.stage == 1:
Yes it's possible, but variable would be available only after function execution:
### file agRead.py ###
def read():
# some code there
read.my_super_var = 'value'
### file agMain.py ###
import agRead
agRead.read()
print(agRead.read.my_super_var) # value
Okay, so I have worked this out. Thanks to everyone who answered, but holdenweb and nightcrawler especially. I have created a class in the agRead.py, and put all of the variables as a part of that class, before returning the class. Here is my agRead.py now:
import os
import operator
import sys
import agSave
import agCreation
class Conf(object):
pass
# READ FUNCTION
def read():
try:
open("agData.txt", "r")
except:
exec(open("agCreation.py").read())
file = open("agData.txt", "r")
data = file.readlines(0)
encrypFName = data[0]
encrypSName = data[1]
encrypAge = data[2]
encrypGender = data[3]
encrypHealth = data[4]
encrypMaxHealth = data[5]
encrypArmour = data[6]
encrypMaxArmour = data[7]
encrypHealthPotions = data[8]
encrypExp = data[9]
encrypMaxExp = data[10]
encrypLevel = data[11]
encrypGold = data[12]
encrypMaxGold = data[13]
encrypPowerLevel = data[14]
encrypMaxPowerExp = data[15]
encrypPowerExp = data[16]
encrypStage = data[17]
conf = Conf()
conf.fName = encrypFName.strip()
conf.sName = encrypSName.strip()
conf.age = encrypAge.strip()
conf.gender = encrypGender.strip()
conf.health = encrypHealth.strip()
conf.maxHealth = encrypMaxHealth.strip()
conf.armour = encrypArmour.strip()
conf.maxArmour = encrypArmour.strip()
conf.healthPotions = encrypHealthPotions.strip()
conf.exp = encrypExp.strip()
conf.maxExp = encrypMaxExp.strip()
conf.level = encrypLevel.strip()
conf.gold = encrypGold.strip()
conf.maxGold = encrypMaxGold.strip()
conf.powerLevel = encrypPowerLevel.strip()
conf.maxPowerExp = encrypMaxPowerExp.strip()
conf.powerExp = encrypPowerExp.strip()
conf.stage = encrypStage.strip()
return conf
and my agMain.py:
# Main
# Will open a stage depending on the stage the user is at.
import os
import operator
import sys
import agSave
import agRead
#Read the file
while True:
agRead.read()
if (conf.stage == 1):
exec(open("agStage1.py").read())
elif (conf.stage == 2):
exec(open("agStage2.py").read())
elif (conf.stage == 3):
exec(open("agStage3.py").read())
elif (conf.stage == 4):
exec(open("agStage4.py").read())
elif (conf.stage == 5):
exec(open("agStage5.py").read())
elif (conf.stage == 6):
exec(open("agStage6.py").read())
elif (conf.stage == 7):
exec(open("agStage7.py").read())
elif (conf.stage == 8):
exec(open("ageStage8.py").read())
elif (conf.stage == 9):
exec(open("agStage9.py").read())
elif (conf.stage == 10):
exec(open("agStage10.py").read())
elif (conf.stage > 10):
for i in range(100):
print("Game over!")
print("****************")
print("Well done, you have completed the game!")
exit()
else:
print("An error has occured.")
continue
And this works perfectly, thank you everyone! This is an amazing community, and I hope to become a real member of it! Thanks again!
Related
I am trying to remove those if situations as much as I can. Here, I do have two if statements and I would like to write the same codes with one or none.
def ai_player(self, state, team = 1):
new_shape_x = np.asarray(state[1]).shape
player1 = Minimax(n = new_shape_x, default_team = team)
if team == -1:
state = player1.convert_board_state(state)
best_move = player1.decision_maker(state)
chosen_succ, utility = best_move
if team == -1:
chosen_succ = player1.convert_board_state(chosen_succ)
return chosen_succ
No Error, it is working fine with extra line codes.
You can split the logic from team == -1 from the logic that happens when team != -1:
def ai_player(self, state, team = 1):
new_shape_x = np.asarray(state[1]).shape
player1 = Minimax(n = new_shape_x, default_team = team)
if team == -1:
state = player1.convert_board_state(state)
best_move = player1.decision_maker(state)
chosen_succ, utility = best_move
chosen_succ = player1.convert_board_state(chosen_succ)
else:
best_move = player1.decision_maker(state)
chosen_succ, utility = best_move
return chosen_succ
There will be a repetition of code though.
In this case, you could also turn the two lines that repeat into one, making it clear that this part of the code is the part that repeats:
def ai_player(self, state, team = 1):
new_shape_x = np.asarray(state[1]).shape
player1 = Minimax(n = new_shape_x, default_team = team)
if team == -1:
state = player1.convert_board_state(state)
chosen_succ, utility = player1.decision_maker(state)
chosen_succ = player1.convert_board_state(chosen_succ)
else:
chosen_succ, utility = player1.decision_maker(state)
return chosen_succ
Now the variable best_move is gone. If you wanna still say that you are choosing the best move there, you could rename the decision_maker method to something like choose_best_move:
def ai_player(self, state, team = 1):
new_shape_x = np.asarray(state[1]).shape
player1 = Minimax(n = new_shape_x, default_team = team)
if team == -1:
state = player1.convert_board_state(state)
chosen_succ, utility = player1.choose_best_move(state)
chosen_succ = player1.convert_board_state(chosen_succ)
else:
chosen_succ, utility = player1.choose_best_move(state)
return chosen_succ
And there it is!
What is wrong with those perfectly readable if-statements?
As a not-totally serious option, you can replace any if with a dict lookup:
# ...
options = {
False: lambda: None
True: lambda: player1.convert_board_state(state)
}
options[team==-1]()
# ...
To make it even more concise (i.e. obscure), you can also use list. Indexing with False gives item 0 and with True gives item 1:
# ...
[
lambda: None,
lambda: player1.convert_board_state(state)
][team==-1]()
# ...
I am trying to write a program (API testing) to loop through instance methods in a class. One of the methods "get_one_sale_license" has a variable "self.sale_sgid_in_test" I need to assign this variable each element in the list "sale_list_final" .The variable is used in the instance method as well as the main function. I put a for loop outside the class and it works fine with the output( this is modified part of a single file from the application using framework).
However, I want to remove the loop wrapping the class and try in a more pythonic way.
import json
from datetime import *
from N import NSession
from N import NArgParser
from i_data_provider import iDataProvider
sale_list = open("sales.txt").readlines()
sale_list_final = [s.rstrip() for s in sale_list]
tests_list = open("tests.txt").readlines()
tests_list_final = [t.rstrip() for t in tests_list]
cnt=0
cnt2=0
cnt3=0
cnt6=0
cnt11=0
for i in sale_list_final:
class iDeployChecks:
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
# self.sale_sgid_list = []
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
def get_all_saleable_sales(self):
global cnt2
if cnt2 == 0:
self.i_session.get_sale_seller_info()
self.logger.info('SUCCESS..... Get all sales api\n')
cnt2 += 1
def get_all_sale_dashboard(self):
global cnt6
if cnt6 == 0:
self.i_session.get_All_sale()
self.logger.info('SUCCESS..... Get all sales on dashboard api\n')
cnt6 += 1
def get_current_user_sale_dashboard(self):
global cnt11
if cnt11 == 0:
self.i_session.get_current_user_sale()
self.logger.info('SUCCESS..... Get current sales on dashboard api\n')
cnt11 += 1
def get_one_sale_license(self):
self.logger.info('Getting sale details from:')
self.sale_sgid_list1 = [item.get('salesgid') for item in self.i_session.get_sale_seller_info()]
#self.sale_sgid_list =[item.get('salesgid') for item in self.i_session.get_sale_seller_info() if item.get('salesgid') == i]
print " for sale " + str(i)
self.sale_sgid_in_test = ''.join(i)
self.logger.info('\n')
self.logger.info('Get License for sale with sale sgid {}'.format(self.sale_sgid_in_test))
self.i_session.get_sale_license(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... Get license api\n')
def get_weekly_stats_count(self):
global cnt
if cnt == 0:
self.i_session.get_weekly_statistics()
self.logger.info('SUCCESS..... Weekly statistics api\n')
cnt += 1
def get_sconfig_value_count(self):
self.i_session.get_sconfig_value(self.sale_sgid_in_test)
self.logger.info('SUCCESS..... sconfig api\n')
def main(self):
start = datetime.utcnow()
# check if the method in the list is present in the class, if yes run it.
for j in tests_list_final:
k = "self." + j + "()"
l= [x.strip() for x in j.split(',')]
m= "self."+l[0]+"(self,year)"
n= "self."+l[0]+"(self,year,month)"
if k == str("self.get_all_saleable_sales()"):
if cnt2 == 0:
self.logger.info('Get All sales')
self.get_all_saleable_sales()
self.logger.info('checking if sale with GSID ' + i + ' exists')
if i not in str(self.i_session.get_sale_seller_info()):
print "the sale with GSID " + i + " does not exist !!"
end1 = datetime.utcnow()
self.logger.info('i health check completed in {} seconds.'.format((end1 - start).seconds))
return
else:
print "sale exists !!"
continue
elif k == str("self.get_one_sale_license()"):
self.get_one_sale_license()
continue
elif k == str("self.get_sale_node_status_value()"):
try:
self.logger.info('Get sale node status for sale sgid {}'.format(self.sale_sgid_in_test))
self.get_sale_node_status_value()
except Exception as e: print e
else:
global cnt3
if (cnt3==0):
print '\n'
print " The testcase " +k + "test does not exist,please recheck test name !!"
print '\n'
cnt3 +=1
end = datetime.utcnow()
self.logger.info('IBDL health check completed in {} seconds.'.format((end - start).seconds))
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
iDeployChecks(args.badge, args.environment).main()
Remove the loop and include in the init
def __init__(self, badge, environment):
self.session = NSession(badge=badge,environment=environment)
self.logger = self.session.logger
self.sale_sgid_list = [i for i in sale_list_final]
self.sale_sgid_in_test = ''
self.i_session = iDataProvider(self.session)
Then loop for the same list element while calling the main
if __name__ == '__main__':
parser = NArgParser(description='i Checks')
args = parser.parse_args()
for i in sale_sgid_list:
iDeployChecks(args.badge, args.environment,i).main()
I am developing a breadth-first-search algorithm for a factorization problem and am running into an interesting/confusing bug when attempting to break out of a while loop. If you run the code below, it will fail inside the "construct_path" method, stating :
File "main.py", line 96
break
SyntaxError: 'break' outside loop
but I am inside of a while loop! If anyone could give me some advice on this issue, I would really appreciate it. Thanks in advance.
from numpy import random
import itertools
import Queue
#Finding multiples, BFS problem
#Given input of list with unique integers 0 - 9 and n = range(0,1000000), calculate smallest multiple of n and unique combination of values in the list
#Example : Input : list = {0,1,2} , n = 3,
# output = 12
# Input : list = {0,1,2} , n = 50
# Output = 200
class Problem:
def __init__(self):
self.n = random.randint(0,10000000)
listSize = random.randint(1,9)
mainSet = set()
self.mainList = []
while True:
toAdd = random.randint(0,9)
if(toAdd not in self.mainList):
self.mainList.append(toAdd)
if(len(self.mainList) == listSize):
break
def get_start_state(self):
s = ''.join(map(str, self.mainList))
return int(s)
def is_goal(self, state):
return True
def get_sucessors(self):
print "Getting successors"
def breadth_first_search(problem):
# a FIFO open_set
open_set = Queue.Queue()
# an empty set to maintain visited nodes
closed_set = set()
# a dictionary to maintain meta information (used for path formation)
meta = dict() # key -> (parent state, action to reach child)
# initialize
start = problem.get_start_state()
meta[start] = (None, None)
open_set.put(start)
while not open_set.empty():
parent_state = open_set.get()
print "{} {}".format("parent_state is ", parent_state)
if problem.is_goal(parent_state):
return construct_path(parent_state, meta)
for (child_state, action) in problem.get_successors(parent_state):
if child_state in closed_set:
continue
if child_state not in open_set:
meta[child_state] = (parent_state, action)
open_set.put(child_state)
closed_set.add(parent_state)
#collect path to desired answer
def construct_path(state, meta):
action_list = list()
while True:
row = meta[state]
if (len(row) == 2):
state = row[0]
action = row[1]
action_list.append(action)
else:
break
return action_list.reverse()
x = Problem()
breadth_first_search(x)
Could be that you have a mix of tabs and spaces so that the break in line 96 looks like it is indented to be below action_list.append(action) but effectively it is below the while. That would explain the error at least.
It is just a guess. But it could be like this, using a visible tabwidth of 4 in the editor:
→ while True:
→ → row = meta[state]
if (len(row) == 2):
state = row[0]
action = row[1]
action_list.append(action)
else:
break
To the Python interpreter this looks like this (because it assumes a tabwidth of 8):
→ while True:
→ → row = meta[state]
if (len(row) == 2):
state = row[0]
action = row[1]
action_list.append(action)
else:
break
This is still valid but obviously means a different thing and would put your break outside of the while loop.
Alright so what I am trying to do is to get objects to save in list form when a user creates a NoteSet. It appends the objects to the list db properly when I input NoteSet('ex','example',True). I made a function called makeNewNoteSet() and it seems to be working correctly but it doesnt append to the db list. I can not figure out why.
import sys
import datetime
import pickle
notesets = []
db = []
def save():
global db
filename = "notesets.dat"
file = open(filename, "wb")
if file == None:
print("There was an error creating your file")
return
pickle.dump(db, file)
file.close()
print("Saved words to ",filename)
def load():
global db
filename = "notesets.dat"
file = open(filename, "rb")
db = pickle.load(file)
print("There are ",len(db)," Note Sets")
file.close()
class NoteSet:
nextseqNum = len(db)+2
def __init__(self,name,description,hidden):
global db
self.seqNum = NoteSet.nextseqNum
self.name = name
self.description = description
self.dateCreated = datetime.date.today()
self.hidden = hidden
self.notes = list()
NoteSet.nextseqNum += 1
print(self)
notesets.append(self)
notelist = [self.seqNum,self.name,self.description,self.dateCreated,self.hidden,self.notes]
print(notelist)
db.append(notelist)
NoteSet.nextseqNum += 1
def __str__(self):
printstr = str(self.seqNum),self.name,self.description,str(self.dateCreated)
printstr = str(printstr)
return printstr
class Note:
nextseqNum = 0
def __init__(self,text,dateCreated,description,category,priority,hidden):
self.text = text
self.dateCreated = str
self.dateRead = str
self.description = str
self.category = str
self.priority = int
self.hidden = bool
self.seqNum = Note.nextseqNum
Note.nextseqNum += 1
def main():
while True:
load()
printMainMenu()
selection = int(input("? "))
if selection == 1:
listNoteSets()
elif selection == 2:
listAllNoteSets()
elif selection == 3:
makeNewNoteSet()
elif selection == 4:
selectNoteSet() # this makes the working note set
elif selection == 5:
deleteNoteSet()
elif selection == 6:
sys.exit()
else:
print("Invalid choice")
def printMainMenu():
print("1. List note sets")
print("2. List all note sets (including hidden sets)")
print("3. Make a new note set")
print("4. Select a working note set")
print("5. Delete a note set")
print("6. Quit")
def listNoteSets():
num = 0
for row in db:
if db[num][4] == False:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def listAllNoteSets():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
input("[Press return to see main menu]")
main()
def makeNewNoteSet():
num = 0
name = input("What would you like to name your note set? --- ")
for row in db:
if name == db[num][1]:
print("That note set has already been created")
makeNewNoteSet()
description = input("Describe your note set briefly --- ")
hidden = input("Would you like this note set to be hidden? --- ")
if hidden == 'y' or 'yes':
hidden = True
else:
hidden = False
NoteSet(name, description, hidden)
print("noteset created you can now access it through the menu")
input("[Press enter to return to menu]")
main()
def selectNoteSet():
num = 0
for row in db:
print('#',db[num][0],' ',db[num][1],'----',db[num][2])
num += 1
response = input("Enter the number assosciated with the noteset you would like to access")
print("Note set #",response," was selected")
main()
After you add a new note in makeNewNoteSet(), you call main() which calls load() which overwrites the in-memory copy of the database you just changed. You probably want to call save() somewhere in there.
I've just started working with the Pickle module in Python 3.4.0 and trying to apply it to a simple program which handles Categories and Words. So far it stores everything as planned, but when I try to load back what I had dumped into the file, the structure appears to be empty:
new_data = int(input("New Data File?\n 1 = Yes\n 0 = No\nChoice: "))
if (new_data == 1):
f = open('data.txt', 'wb+')
data_d = {}
pickle.dump(data_d, f)
f.close()
PrMenu()
option = int(input("Option: "))
f = open('data.txt', 'rb+')
d = pickle.load(f)
#Functions inside this menu loop receive the structure (Dictionary)
#and modify it accordingly (add/modify/clear category/word), no
#pickling/unpickling is involved
while (option != 0):
if (option == 1):
add_c(d)
elif (option == 2):
modify_c(d)
elif (option == 3):
clear_c(d)
elif (option == 4):
add_w(d)
elif (option == 5):
modify_w(d)
elif (option == 6):
clear_w(d)
elif (option == 7):
pr_cw(d)
elif (option == 8):
pr_random(d)
if (option != 0):
PrMenu()
option = int(input("Option: "))
#the output structure would be eg. {category_a:[word1, word2, word3, ...], category_b:[..., ...]}
pickle.dump(d, f)
f.close()
print("End of Program")
I'm not sure where the problem is, I hope I was clear enough.
Thanks.
You are appending data to your file. so the first dataset is the empty dictionary, which you read in, and the second dataset is the filled dictionary, which you never read again. You have to seek back to 0 before writing.