python - 连接两个字符串时Python无法找到变量
问题描述
这似乎是一个非常愚蠢的问题,但它让我很生气。我几天前才开始使用 Python,在使用其他语言一段时间后,我遇到了一个非常奇怪的问题。我正在尝试将一个名为“word”的顶级字符串变量设置为自身和一个字母的连接。Python 能够很好地找到变量,如下所示。
但是,每当我尝试连接时,我都会突然收到一条错误消息,告诉我 Python 无法找到该变量。
黄色波浪线是我的 IDE,告诉我找不到该变量。我已经尝试直接从其他堆栈交换帖子中直接复制+粘贴其他解决方案。在连接方面遇到这么多麻烦有点尴尬,但我已经尝试了大部分我能想到的东西。
编辑:这是我的代码。如您所见,“word”在文件顶部初始化:
word_dict = PyDictionary()
repeats = 5
word = "e"
def handle_input(x, y, letter):
word += letter
print(word)
coords = make_coords(x, y)
for list in grid:
for button in list:
button.update(disabled=True)
for coord in coords:
x = coord[0]
y = coord[1]
list = grid[y]
button = list[x]
button.update(disabled=False)
解决方案
由于您word
是在函数之外定义的,因此您需要将其重新声明为全局变量:
def handle_input(x, y, letter):
global word #add this line
word += letter
print(word)
coords = make_coords(x, y)
for list in grid:
for button in list:
button.update(disabled=True)
for coord in coords:
x = coord[0]
y = coord[1]
list = grid[y]
button = list[x]
button.update(disabled=False)
推荐阅读
- python - 为 pytorch 安装预训练模型时出错
- .htaccess - 如何设置数据库驱动的永久链接
- c - 使用 fseek 打印任意记录
- firebase - Firebase 事件是如何计算的?
- django - 开发时如何在 Kubernetes 上保持 Django 2.2 迁移?
- excel - 如何根据某些单元格中的条目创建消息框?
- html - 如何使用 Firebase 云功能发送 http 链接作为响应
- google-chrome - 为什么我的 Herokuapp 在 Chrome 上是安全的,但在 Microsoft Edge 上不安全?
- angular - jhipster 过滤器结果正确返回,但是当我单击 UI 导航到结果集中的第 2 页时,我再次获得未过滤的结果
- javascript - 在 React 中使用 List 和 map 时触发第一个列表项