
本文详解 python 缩进对条件执行流的关键影响,通过修复“宝可梦游戏中的地点选择逻辑错误”,说明如何用正确缩进将商店购买流程嵌套在 `if place_1 == "pokemart"` 分支内,避免 `else` 被错误关联,从而真正实现“去宝可梦商店”与“进高草丛”的二选一分支控制。
在 Python 中,缩进不是格式美化,而是语法核心——它明确标识代码块的从属关系。你原代码的问题正源于此:pokemart_1 = input(...) 及其后续判断未被缩进到 if place_1 == "pokemart": 的代码块中,导致无论玩家输入什么,程序都会执行购买询问;而 else: print("You go to the tall grass") 实际上与最外层的 if 配对,但因中间代码“悬空”,逻辑已完全错位。
✅ 正确做法是:将整个商店交互流程(包括输入、判断、消费逻辑)整体缩进至 if place_1 == "pokemart": 下,使 else 真正成为该 if 的对立分支:
# 假设初始资金已定义(否则会报 NameError)
money = 500
place_1 = input("Where do you want to go? (pokemart/tall grass): ").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.")
# ✅ 全部缩进至此处 —— 属于 pokemart 分支内部
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,确保只有非 pokemart 输入才触发
print("You go to the tall grass")
print("... rustling sounds ... A wild Pidgey appears!")⚠️ 注意事项:
- 务必统一缩进:推荐使用 4 个空格(而非 Tab),多数编辑器可配置为自动转换;
- .strip().lower() 提升健壮性:避免因空格或大小写导致匹配失败;
- 变量初始化不可省略:如 money 未提前定义,运行时将抛出 NameError;
- else 永远匹配最近的、未被闭合的 if:检查缩进层级,用 IDE 的缩进引导线辅助验证。
总结:Python 的控制流由缩进定义,而非大括号或关键字。一次缩进失误,就可能让“高草丛冒险”永远被跳过。养成「写完 if 立即回车缩进、写完代码块立即补 else 或 elif」的习惯,是写出可靠交互逻辑的第一步。
立即学习“Python免费学习笔记(深入)”;










