Python中的作用域有一个问题,变量声明为全局变量,但仍然会出错
即使在将变量声明为全局变量之后Python中的作用域有一个问题,变量声明为全局变量,但仍然会出错,python,variables,scope,global-variables,local,Python,Variables,Scope,Global Variables,Local,即使在将变量声明为全局变量之后 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 h
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
出于某种原因,它说局部变量在赋值之前就被引用了,即使它被赋值和全局化了,正如错误消息所述,您在赋值之前引用了隐藏的单词
def wordFiller(word,letter):
hidden_wordTemp = hidden_word.split()
在wordFilter的范围内,您从未初始化隐藏的单词。确保在使用变量之前对其进行初始化。wordFiller函数中的隐藏单词仍然是该函数的局部变量。尝试在该功能中使其全局化
def wordFiller(word,letter):
global hidden_word
hidden_wordTemp = hidden_word.split()
// etc
另外,randintstart,end函数包含start和end,因此可以生成end值。这将超出阵列的范围。试试这个
randomNum = random.randint(0, len(categorie) - 1)
最后,斯普利特可能并没有做你们认为的事情。如果需要字符列表,请使用liststr
谢谢!一切都解决了!我一运行程序就得到了超出范围的错误,所以你的评论非常有用!谢谢你提到分裂。我会调查的!再次非常感谢,解决了
hidden_wordTemp = list(hidden_word)