我在 Python 中的范围有问题,声明为全局变量但仍然出错

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

即使在将变量声明为全局变量之后

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')

错误输出如下:

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

出于某种原因,它说局部变量在赋值之前被引用,即使它已被赋值并且 "globaled"

正如错误消息所述,您在分配之前引用了 hidden_word

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

wordFilter 的范围内,您从未初始化 hidden_word。确保在使用变量之前初始化变量。

wordFiller 函数中的

hidden_word 仍然是该函数的局部变量。也尝试在该函数中将其设为全局。

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

此外,randint(start, end) 函数包含开始和结束,因此您可以生成结束值。那将超出您的数组范围。试试这个。

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

最后,split() 可能并没有按照您的想法行事。如果您想要字符列表,请改用 list(str)

 hidden_wordTemp = list(hidden_word)