Python条件嵌套:多分支逻辑正确缩进技巧
本文详解Python条件语句中缩进的关键作用,通过修复宝可梦小游戏中的“地点选择逻辑错误”,说明如何用正确嵌套结构实现玩家在宝可梦商店与草丛之间的可控跳转。

本文详解 Python 条件语句中缩进的关键作用,通过修复宝可梦小游戏中的“地点选择逻辑错误”,说明如何用正确嵌套结构实现玩家在宝可梦商店与草丛之间的可控跳转。
在 Python 中,缩进不是风格偏好,而是语法必需。它直接定义代码块的归属关系——尤其是 if、elif、else 等控制结构中,缩进层级决定了某段代码是否属于某个条件分支的执行体。
你遇到的问题正是典型缩进缺失导致的逻辑失控:原代码中 pokemart_1 = input(...) 及其后续判断未被包含在 if place_1 == "pokemart": 块内,因此无论用户输入什么,程序都会无条件执行购买询问;而 else: print("You go to the tall grass") 实际上只与最外层 if 配对,但因缩进错位,其触发时机完全偏离预期(例如输入 "tall grass" 时本应直接进入草丛,却仍会先执行商店流程)。
✅ 正确写法需严格保证逻辑层级一致:
# 初始化示例(实际项目中需提前定义)
money = 500
place_1 = input("Where do you want to go? ").strip().lower()
if place_1 == "pokemart":
print("You go to the pokemart")
print("Seller: Hello! Welcome to the pokemart!")
print("Seller: Hi! I work at a POKEMON MART. It's a convenient shop, so please visit us in VIRIDIAN CITY. I know, I'll give you a sample! Here you go!")
print("You get 3 potions and 3 pokeballs")
print("Customer: See those ledges along the road? It's a bit scary, but you can jump from them. You can get back to PALLET TOWN quicker that way.")
# ✅ 关键:此处整体缩进4个空格(或1个Tab),成为 if 块的子逻辑
pokemart_1 = input("Would you like to buy a potion or a pokeball? ").strip().lower()
if pokemart_1 == "potion":
print("You spend 100 pokedollars on a potion")
money -= 100
print(f"Remaining money: {money}")
elif pokemart_1 == "pokeball":
print("You spend 100 pokedollars on a pokeball")
money -= 100
print(f"Remaining money: {money}")
else:
print("Invalid choice. You leave the pokemart.")
else:
# ⚠️ 此 else 对应最外层 if,仅当 place_1 不为 "pokemart" 时触发
print("You go to the tall grass")
print("Wild Pidgey appears!")? 重要注意事项:
- 使用 统一缩进方式(推荐 4 个空格),避免混用 Tab 与空格,否则易引发 IndentationError;
- .strip().lower() 可提升输入鲁棒性,忽略大小写和首尾空格(如 "POKEMART " 或 " pokemart");
- money 变量需在使用前初始化(如 money = 500),否则将触发 NameError;
- 若未来扩展更多地点(如 "gym"、"pokecenter"),建议改用 elif 链或字典分发模式,保持可维护性。
掌握缩进即掌握 Python 的控制流骨架。一次正确的缩进,让游戏逻辑从“自动跳转”变为“真正由玩家选择”——这正是交互式程序设计的起点。
Photoshop 2026 是 Adobe 推出的专业图像处理与视觉设计软件,支持 Windows、macOS 和 iPad 等平台,广泛应用于摄影修图、电商设计、平面海报、数字绘画及视觉合成等创作场景。
Blender 是一款免费开源、跨平台的专业 3D 创作软件,集建模、动画、渲染、视频编辑与视觉合成等功能于一体,广泛应用于影视动画、游戏设计和建筑可视化等领域。软件支持 Cycles 物理渲染器与 Eevee 实时渲染引擎,并提供多边形建模、骨骼绑定、物理模拟等专业工具。Blender 兼容 Windows、macOS 和 Linux 系统,安装包轻巧、运行流畅,依托活跃的全球开发者社区持续更新,是从初学者到专业创作者都值得选择的正版 3D 创作工具。
Photoshop 2026 是 Adobe 推出的专业图像处理与视觉设计软件,支持 Windows、macOS 和 iPad 等平台,广泛应用于摄影修图、电商设计、平面海报、数字绘画及视觉合成等创作场景。
Blender 是一款免费开源、跨平台的专业 3D 创作软件,集建模、动画、渲染、视频编辑与视觉合成等功能于一体,广泛应用于影视动画、游戏设计和建筑可视化等领域。软件支持 Cycles 物理渲染器与 Eevee 实时渲染引擎,并提供多边形建模、骨骼绑定、物理模拟等专业工具。Blender 兼容 Windows、macOS 和 Linux 系统,安装包轻巧、运行流畅,依托活跃的全球开发者社区持续更新,是从初学者到专业创作者都值得选择的正版 3D 创作工具。















