python - 当在其中使用全局变量时,函数变得不可迭代
问题描述
这里的初学者,我对解决问题很感兴趣,但也学习它的“如何”和“为什么”
所以我有这个功能:
import random
move = 0
def computer_move():
global move
if move == 0:
while True:
rand = random.randrange(0, 9)
if positions[rand].state:
move = 1
positions[rand].state = False
positions[rand].played = 'circle'
return positions[rand].x,positions[rand].y
在我在函数外部声明“move”变量之前,一切正常,除非每当调用函数时变量重置为 0,所以我必须在外部声明它,自然我必须将它与global
. 除了现在当我像这样调用函数时:
x, y = computer_move()
我TypeError: cannot unpack non-iterable NoneType object
上线了函数调用
我厌倦了一些想法,但似乎没有任何效果。感谢任何帮助或澄清
解决方案
None
在 Python 中,如果没有return
执行,则函数返回。如果 .你的函数可能会None
像这样返回move != 0
。在这种情况下,x, y = computer_move()
将等价于x, y = None
,这会导致TypeError
.
推荐阅读
- python - 将随机整数值添加到列表中的元素,但列表的总和不得更改
- matlab - 基本矩阵和基本矩阵会随着不同的照片而变化吗?
- azure-web-app-service - 容器应用服务的 Azure 门户应用设置
- c++ - CodeBlocks、C++、mingw-w64 编译器、Windows 10、错误:对“DAQmxCreateTask”的未定义引用等
- docker - Odoo 配置文件 unicode 问题
- spacy - 基于 Spacy 规则的匹配未按预期返回匹配
- java - WebApp 之间的 JDBC ConnectionPool 共享
- javascript - 页面刷新后 AJAX 调用停止
- python - 用 Python 和 Django 在午夜结束一个活动
- git - 如何在 Git 存储库中查找第一个版本的提交