Home Python: global not defined / local var referenced before assignment
Reply: 1

Python: global not defined / local var referenced before assignment

ib- Published in 2017-12-05 06:48:20Z

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]:
    for i in range(len(aCVals)):
        if aCKeys[i] in possiblePitches:
        elif aCKeys[i] == '$:::$': 
    isDictionaryEmpty = bool(constrainedCandidates)
    if isDictionaryEmpty == True:
        q = self.weightedChoice(constrainedCandidates)
        return q
        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


Thu Yein Tun
Thu Yein Tun Reply to 2017-12-05 06:53:38Z

You defined 2 global variables as aCVals and aCKeys. And the first for loop is calling acVals not aCVals. Python is case sensitive, so they're two different variables, as such, python throws acVAls is not defined error.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.307975 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO