python - 我在 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
出于某种原因,它说局部变量在赋值之前被引用,即使它被赋值并“全局化”
解决方案
hidden_word
wordFiller 函数内部仍然是该函数的局部变量。尝试在该功能中使其成为全局。
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)
推荐阅读
- java - Java Jackson反序列化实现接口的抽象类子
- shell - variable=$(...) 是否将命令或命令的结果存储在 POSIX sh 中
- r - 如何嵌套小标题
- java - Eclipse动态web项目的Tomcat安装配置
- mysql - MySQL 8 st_distance_sphere 为不同的 SRID 提供不同的值
- r - 计算条件为 2.0 的观测值之和
- sql-server - 无法远程连接到 vb.net 中的 sqlserver
- sql - 从三个表和日期范围相等的地方获取数据
- python-3.x - 芹菜是长时间运行任务的好选择吗?
- azure-devops - Azure DevOps Rest API - 按标签/标签列出拉取请求