Order of execution in Python methods
python
Solution
`global` means that within the function containing the `global` declaration, the name in the `global` declaration refers to a global variable. It does not mean "this thing is a global variable; treat it as global everywhere." In `main`, the names `count` and `myDict` refer to local variables, because `main` does not declare that it wants to use the globals.
Problem
I've tried looking at a few different examples, but I'm not really sure why this isn't working. Say I've some 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() ``` To my eyes, the if statement is executed which starts the main() method. Then, the variable which is global is loaded, the dictionary is loaded and the for loop is executed. However, when I run the code I am told that the local variable count is referenced before its assignment. Why is that happening? Edit (Explaining some of the things I've written in comments): This doesn't work (although I think that's because global is used wrong here): ``` global count def loadVariables() count = 0 def main(): loadVariables() rest of code etc ``` This doesn't work either: ``` def loadVariables() count = 0 def main(): global count loadVariables() rest of code etc ``` The only way thus far I've gotten it to work is using the link provided above, which is to treat the count as a list, like so: ``` def loadVariables(): global count count = [0] def main(): loadVariables(): rest of code etc count[0] += 1 ```