You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python宝可梦选择函数BUG排查:无效输入判定异常问题

修复宝可梦选择函数中的逻辑错误

问题根源

你的代码核心问题在于if语句的逻辑表达式写错了:

if userinput1 == f"{Pokemon1}" or f"{Pokemon2}" or f"{Pokemon3}":

这个写法不符合Python布尔判断逻辑——or后面的f"{Pokemon2}"和f"{Pokemon3}"是 non-empty字符串,会被直接判定为True。这导致无论用户输入什么,if条件都会成立,else分支永远不会触发。

同时外层while循环条件是userinput1 not in choices1,所以就算输入无效内容,if代码执行后循环仍会继续,出现"错误提示不显示、一直困在循环里"的矛盾现象。

修复方案

提供两种逻辑正确且简洁的写法:

写法一:保留原循环结构,修正判断逻辑

def pkmn_choice1():
    Pokemon1 = Pokemon_dct[f'{random_pkmn1}'].pokechoice()
    Pokemon2 = Pokemon_dct[f'{random_pkmn2}'].pokechoice()
    Pokemon3 = Pokemon_dct[f'{random_pkmn3}'].pokechoice()
    choices1 = [Pokemon1, Pokemon2, Pokemon3]
    print("Choose one of these Pokemon to fight with.")
    userinput1 = ""
    
    while userinput1 not in choices1:
        print(f"Options: {Pokemon1}, {Pokemon2}, or {Pokemon3}.")
        userinput1 = input().strip()  # 过滤输入前后空格,避免误判
        
        if userinput1 in choices1:
            print(f'You have chosen {userinput1} to be your partner.')
            Pokemon_dct[userinput1].pokeinfo1()
        else:
            print("That was not a valid selection. Please try again")

写法二:用while True+break简化逻辑(更推荐)

这种写法无需维护初始值,逻辑更直观:

def pkmn_choice1():
    Pokemon1 = Pokemon_dct[f'{random_pkmn1}'].pokechoice()
    Pokemon2 = Pokemon_dct[f'{random_pkmn2}'].pokechoice()
    Pokemon3 = Pokemon_dct[f'{random_pkmn3}'].pokechoice()
    choices1 = [Pokemon1, Pokemon2, Pokemon3]
    print("Choose one of these Pokemon to fight with.")
    
    while True:
        print(f"Options: {Pokemon1}, {Pokemon2}, or {Pokemon3}.")
        userinput1 = input().strip()
        
        if userinput1 in choices1:
            print(f'You have chosen {userinput1} to be your partner.')
            Pokemon_dct[userinput1].pokeinfo1()
            break  # 选择正确后直接跳出循环
        else:
            print("That was not a valid selection. Please try again")

关键改动说明

  1. 修正判断逻辑:用userinput1 in choices1替代错误的or表达式,简洁且与循环条件保持一致,避免逻辑冲突。
  2. 处理输入空格:给input()添加.strip(),过滤用户输入时误加的前后空格,避免因空格导致的无效判断。
  3. 简化字符串操作:Pokemon1本身是pokechoice()返回的字符串,无需额外用f"{Pokemon1}"格式化。

内容的提问来源于stack exchange,提问作者James Chin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 07:53:10