Python新手求助:全局变量seek_goal无法修改为True的问题排查
Reeborg迷宫初始化Bug修复:全局变量不更新问题
核心问题是函数内部对seek_goal的赋值未修改全局变量,而是创建了同名局部变量,导致外层while循环始终检测全局seek_goal为False,无法退出初始化阶段。
问题原因
在Python中,函数内部直接给变量赋值时,默认会将其视为局部变量,即便全局作用域存在同名变量。你的init_homing函数中seek_goal = True语句,实际是定义了一个局部的seek_goal,和全局变量毫无关联。
修复方案
方案一:使用global关键字声明全局变量
在init_homing函数开头添加global seek_goal,明确告知Python该函数引用的是全局作用域的seek_goal变量:
seek_goal = False def turn_right(): turn_left() turn_left() turn_left() def turn_around(): turn_left() turn_left() def init_homing(): global seek_goal # 声明使用全局变量 if right_is_clear() and front_is_clear(): turn_around() if right_is_clear() and front_is_clear(): turn_right() move() else: seek_goal = True else: seek_goal = True while seek_goal == False: init_homing() while at_goal() == False and seek_goal == True: if right_is_clear(): turn_right() move() elif front_is_clear(): move() else: turn_left()
方案二:让函数返回状态,外层更新变量
避免使用global关键字(更推荐的写法,减少全局变量副作用),让init_homing返回布尔值,外层循环根据返回值更新seek_goal:
seek_goal = False def turn_right(): turn_left() turn_left() turn_left() def turn_around(): turn_left() turn_left() def init_homing(): if right_is_clear() and front_is_clear(): turn_around() if right_is_clear() and front_is_clear(): turn_right() move() return False # 需继续初始化 else: return True # 可退出初始化 else: return True # 可退出初始化 while not seek_goal: seek_goal = init_homing() while not at_goal() and seek_goal: if right_is_clear(): turn_right() move() elif front_is_clear(): move() else: turn_left()
第二种方案更符合函数设计原则,函数专注完成初始化逻辑并返回状态,外层负责更新变量,降低代码耦合度。
内容的提问来源于stack exchange,提问作者Velexter
相关产品推荐
相关产品推荐

