I tried looking at a few different examples, but I'm not quite sure why this is not working. Let's say I have a code like this:
def loadVariable(): global count count = 0 def loadDictionary(): location = 'some location' global myDict myDict = pickle.load(open(location, 'rb')) def main(): loadVariable() loadDictionary() for item in myDict: if item.startswith("rt"): count += 1 item = item[3:] if __name__ == '__main__': main()
In my eyes, the if statement is executed, which runs the main () method. Then the variable that is global is loaded, the dictionary is loaded and the for loop is executed.
However, when I run the code, they tell me that before the assignment, the value of the local variable is referenced. Why is this happening?
Edit (An explanation of some of the things I wrote in the comments):
This does not work (although I think that since global is used incorrectly here):
global count def loadVariables() count = 0 def main(): loadVariables() rest of code etc
This also does not work:
def loadVariables() count = 0 def main(): global count loadVariables() rest of code etc
The only way I got to this is to use the link above, which should treat the account as a list:
def loadVariables(): global count count = [0] def main(): loadVariables(): rest of code etc count[0] += 1
source share