【发布时间】:2019-07-22 15:55:52
【问题描述】:
即使在将变量声明为全局变量之后
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
由于某种原因,它表示局部变量在赋值之前已被引用,即使它已被赋值并“全局化”
【问题讨论】:
标签: python variables scope global-variables local