您的位置:首页 >Python条件嵌套:多分支逻辑正确缩进技巧
发布于2026-02-15 阅读(0)
扫一扫,手机访问

本文详解 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!")? 重要注意事项:
掌握缩进即掌握 Python 的控制流骨架。一次正确的缩进,让游戏逻辑从“自动跳转”变为“真正由玩家选择”——这正是交互式程序设计的起点。
上一篇:《异星探险家》卡利多特详解
下一篇:名片全能王更新提醒查看方法
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
售后无忧
立即购买>office旗舰店
正版软件
正版软件
正版软件
正版软件
正版软件
1
2
3
7
9