Search code examples
pythonvariablesscopeglobal-variableslocal

I have a problem with scopes in Python, Variable declared as global but still get err


even after declaring a variable as global

import random

def wordRandomizer(categorie):
    randomNum = random.randint(0, len(categorie))
    #Picks a random number to pick a word from the list
    choosenWord = categorie[randomNum]
    #actually chooses the word
    global hidden_word
    #Globals the variable that I have the problem with
    hidden_word = "_" * len(choosenWord)
    return choosenWord

def wordFiller(word,letter):
    hidden_wordTemp = hidden_word.split()
    for i in range(len(word)):
        if word[i] == letter:
            hidden_wordTemp[i] = letter
        else:
            pass
    hidden_word = ''.join(hidden_wordTemp)
    print(hidden_word)

wordFiller(wordRandomizer(['book', 'bottle', 'door']), 'o')

The Error output is below:

Traceback (most recent call last):
  File "C:\Users\amitk\OneDrive\School\2018-2019 ט\Cyber\Hangman.py", line 295, in <module>
    wordFiller(wordRandomizer(['book', 'bottle', 'door']), 'o')
  File "C:\Users\amitk\OneDrive\School\2018-2019 ט\Cyber\Hangman.py", line 286, in wordFiller
    hidden_wordTemp = hidden_word.split()
UnboundLocalError: local variable 'hidden_word' referenced before assignment

For some reason it says that the local variable was referenced before assignment even though it was assigned and "globaled"


Solution

  • hidden_word inside the wordFiller function is still a local variable to that function. Try also making it global in that function.

    def wordFiller(word,letter):
       global hidden_word
       hidden_wordTemp = hidden_word.split()
       // etc
    

    Also, the randint(start, end) function is inclusive of start and end so potentially you can generate the end value. That will be outside the scope of your array. Try this instead.

      randomNum = random.randint(0, len(categorie) - 1)
    

    And finally, split() is probably not doing what you think it is. If you want a list of characters then use list(str) instead.

     hidden_wordTemp = list(hidden_word)