Python宝可梦场景选择异常:自动跳转Pokemart问题求助
问题分析
你的代码核心问题是分支结构逻辑混乱,导致场景选择完全失效:
- 前往长草丛的逻辑被错误放在了「购买选项」的else分支里,而非「场景选择」的分支中
- 「购买相关代码」未被包裹在
if place_1 == "pokemart"的代码块内,所以无论选什么场景,都会强制进入购买流程 - 变量
money未初始化,执行时会抛出NameError
修复后的代码
# 初始化金钱变量 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.") # 将购买逻辑嵌套在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} pokedollars") elif pokemart_1 == "pokeball": print("You spend 100 pokedollars on a pokeball") money -= 100 print(f"Remaining money: {money} pokedollars") else: print("You didn't buy anything, leaving the pokemart.") elif place_1 == "tall grass": print("You walk into the tall grass...") print("A wild POKEMON appeared!") else: print("Invalid location, please choose 'pokemart' or 'tall grass'.")
关键修改说明
- 调整分支结构:把购买相关的所有代码移入
if place_1 == "pokemart"的代码块中,确保只有选Pokemart才会触发购买流程 - 补充场景分支:新增
elif place_1 == "tall grass"分支,专门处理进入长草丛的逻辑 - 初始化变量:添加
money = 500避免未定义错误,同时用f-string优化金钱显示格式 - 输入容错处理:给input添加
.strip().lower(),避免用户输入大小写或空格导致匹配失败
内容的提问来源于stack exchange,提问作者Gabbonbon
相关产品推荐
相关产品推荐

