Home Python: global not defined / local var referenced before assignment
 In this code (part of a function definition)  global aCVals global aCKeys i = 0 allCandidates = self.getCandidateDictionary(musicalSentence) constrainedCandidates = {} aCVals = list(allCandidates.values()) aCKeys = list(allCandidates.keys()) for i in range(len(acVals)): if acVals[i] == possiblePitches[i]: constrainedCandidates.append(possiblePitches[i]) for i in range(len(aCVals)): if aCKeys[i] in possiblePitches: constrainedCandidates.append(aCKeys[i]) elif aCKeys[i] == '$:::$': constrainedCandidates.append(aCKeys[i]) isDictionaryEmpty = bool(constrainedCandidates) if isDictionaryEmpty == True: q = self.weightedChoice(constrainedCandidates) return q else: tup = (random.choice(possiblePitches).append(4), random.choice(NOTE_DURATIONS)) return tup  I get the error:  NameError: global name 'acVals' is not defined  The reason I added the globals is because before I put them there I would get this error: local variable 'acVals' referenced before assignment  Please help, and please be thorough in explanation so I gain a better understanding of the concept I'm missing here Thanks