商城首页欢迎来到中国正版软件门户

您的位置:首页 >Python条件嵌套:多分支逻辑正确缩进技巧

Python条件嵌套:多分支逻辑正确缩进技巧

  发布于2026-02-15 阅读(0)

扫一扫,手机访问

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 的控制流骨架。一次正确的缩进,让游戏逻辑从“自动跳转”变为“真正由玩家选择”——这正是交互式程序设计的起点。

本文转载于:互联网 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。

热门关注