lundi 1 juillet 2019

Python UnboundLocalError: Problems with a function for choosing words from a dictionary

I've written a function for choosing a single key (=word) from a dictionary. If the key has already been used, another key should be chosen. This is my function:

nom_acc = {"qeso":"qes", "os":"os", "sondra":"sondre", "mawizzi":"mawizze", "khewo":"khewe", "alegra":"alegre", "kendra":"kendre", "zhalia":"zhalie", "achrakh":"achrakh", "ador":"ador", "hoggi":"hogge", "soqwi":"soqwe"}
usedWords = []

def wordChoice():
    global usedWords
    print(usedWords) ### DELETE LATER

    word = random.choice(list(nom_acc))     ### randomly pick a key from a dictionary (which is the nominative form)
    print(word) ### DELETE LATER 
    if word in usedWords: 
        print("gotta pick another word") ### DELETE LATER
        wordChoice() 
    else: 
        usedWords.append(word)          
        accusative = nom_acc[word]

    return word, accusative

The function is embedded into a main program. When I run the code like this, it gives me an error message as soon as a word is chosen that has already been used: UnboundLocalError: local variable 'accusative' referenced before assignment

If I add a dummy value for the word and accusative variable it seems to work:

    if word in usedWords: 
        print("gotta pick another word") ### DELETE LATER
        word="DUMMY"
        accusative="DUMMY" 

But what I want is that another word is chosen from the dictionary if the word has already been used. How do I implement this?

Aucun commentaire:

Enregistrer un commentaire