Python文本游戏if-else语句中更新变量报未引用错误如何解决
问题原因
这是Python变量作用域规则导致的报错:
- 你在函数外定义的
current_position属于全局变量,默认情况下函数内部仅可读取全局变量,如果要在函数内部修改全局变量,必须先用global关键字声明该变量 - 你的代码在
player_moves_south函数内对current_position做了赋值操作,Python会默认将该变量识别为函数内部的局部变量,但你在if判断逻辑中先读取了这个还未完成定义的局部变量,因此触发了未引用报错
同时你的代码还有两处可优化的问题:
- 连续写了两个
return语句,第一个return player_choice执行后,后续的return current_position永远不会被触发,属于无效代码 - 打印文本存在拼写错误:
welcome too the Bedroom应改为welcome to the Bedroom
修复方案
方案1:用global关键字声明全局变量(快速修复)
current_position = rooms[0] def player_moves_south(): # 声明当前函数要修改的是全局变量current_position global current_position if current_position == rooms[0]: current_position = rooms[1] print('welcome to the Bedroom you can now move North or East') player_choice = input() # 同时返回两个值可以用元组格式 return player_choice, current_position else: print('error') # 所有分支统一返回值避免后续调用报错 return None, None
方案2:用传参+返回值管理状态(更规范,避免全局变量污染)
如果不想使用全局变量,可以把当前位置作为参数传入函数,修改完成后再返回新的位置:
def player_moves_south(current_pos): if current_pos == rooms[0]: new_pos = rooms[1] print('welcome to the Bedroom you can now move North or East') player_choice = input() return player_choice, new_pos else: print('error') return None, current_pos # 调用示例:传入当前位置,接收返回的用户选择和更新后的位置 current_position = rooms[0] player_choice, current_position = player_moves_south(current_position)
内容的提问来源于stack exchange,提问作者rimsky richard
相关产品推荐
相关产品推荐

