首页 > 解决方案 > 我在 Python 中的范围有问题,变量声明为全局但仍然出错

问题描述

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

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\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

出于某种原因,它说局部变量在赋值之前被引用,即使它被赋值并“全局化”

标签: pythonvariablesscopeglobal-variableslocal

解决方案


hidden_wordwordFiller 函数内部仍然是该函数的局部变量。尝试在该功能中使其成为全局。

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)

推荐阅读