Reputation: 75
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"
Upvotes: 0
Views: 43
Reputation: 103135
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)
Upvotes: 1
Reputation: 519
Just as the error message states, you referenced hidden_word
before you assigned it.
def wordFiller(word,letter):
hidden_wordTemp = hidden_word.split()
Inside the scope of wordFilter
you never initialized hidden_word
. Make sure to initialize your variables before you use them.
Upvotes: 0