Python 中的缩进决定逻辑分支:修复嵌套选择逻辑的关键

2026-01-31 00:00:00 作者:聖光之護

本文详解如何通过正确缩进实现“前往宝可梦商店或草丛”的二选一分支逻辑,解决因缩进错误导致程序始终执行 pokemart 分支而忽略 tall grass 的常见问题。

在 Python 中,缩进不是风格偏好,而是语法核心——它明确界定代码块的归属关系。你遇到的问题(无论输入 "tall grass" 还是其他内容,程序都进入 Pokemart 流程)正是由于 pokemart_1 = input(...) 及其后续判断未被正确嵌套在 if place_1 == "pokemart": 的代码块内,导致这部分逻辑脱离条件约束,无条件执行;而 else: print("You go to the tall grass") 实际上只与最外层的 if place_1 == "pokemart" 配对,但因缩进错位,其作用范围被意外破坏。

✅ 正确做法是:将 Pokemart 内部所有交互(购买询问、选项处理、金钱计算)整体缩进至与 print("You go to the pokemart") 对齐,确保它们仅在用户明确选择 "pokemart" 时运行。

以下是修复后的完整逻辑结构(含变量初始化建议):

# 初始化关键变量(避免 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? (potion / 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. No purchase made.") else: # ✅ 此 else 对应最外层 if,确保只有非-pokemart 输入才触发 print("You go to the tall grass") print("Wild Pokémon may appear...!")

⚠️ 注意事项

  • 始终使用 4个空格(推荐)或一致的 Tab 缩进,切勿混用;
  • .strip().lower() 可提升输入鲁棒性,忽略大小写和首尾空格;
  • 在使用 money 前务必初始化(如 money = 500),否则会触发 NameError;
  • else 子句必须与 if 保持相同缩进层级,否则语法错误或逻辑错位。

掌握缩进规则,就是掌握 Python 控制流的钥匙。每一次缩进,都在清晰定义“这段代码属于哪个决策之下”——这是编写可靠交互式程序的第一道防线。

猜你喜欢

联络方式:

400 9058 355

邮箱:8955556@qq.com

Q Q:8955556

微信二维码
在线咨询 拨打电话

电话

400 9058 355

微信二维码

微信二维码