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

如何避免Python程序因元组索引无效终止并重新调用函数

解决宝可梦初始精灵选择的输入异常问题

你原代码的核心问题在于:if(ChosenPok == 1,ChosenPok == 2,ChosenPok == 3)的写法错误,逗号在这里会生成一个非空元组,而Python中非空元组永远被判定为True,导致这个判断完全起不到筛选有效输入的作用。当用户输入超出1-3范围的数字时,代码依然会执行索引取值操作,直接触发索引越界错误导致程序终止。

下面提供两种可行的修改方案:

方案一:提前做输入合法性校验

先验证输入是否为有效数字且在1-3范围内,无效则重新调用选择函数:

try:
    ChosenPokInt = int(ChosenPok)
    # 检查数字是否在有效范围内
    if 1 <= ChosenPokInt <= 3:
        StarterPok = Starter[ChosenPokInt - 1]
        Sure = f"You chose {StarterPok} are you sure? (y/n)"
        YORN = input(Sure)
        if YORN.lower() == "y":
            Congrats = f"Congratulations!! You just got a {StarterPok}!!"
            WriteFast(Congrats)
            print(StarterPok)
        else:
            WriteFast(ERROR)
            ChoseStarter()
    else:
        WriteFast("请输入1-3之间的数字!")
        ChoseStarter()
except ValueError:
    # 处理输入不是有效数字的情况
    WriteFast("请输入有效的数字!")
    ChoseStarter()

方案二:捕获异常直接处理

用try-except捕获索引越界和输入非数字的异常,触发时重新调用选择函数:

try:
    ChosenPokInt = int(ChosenPok)
    StarterPok = Starter[ChosenPokInt - 1]
    Sure = f"You chose {StarterPok} are you sure? (y/n)"
    YORN = input(Sure)
    if YORN.lower() == "y":
        Congrats = f"Congratulations!! You just got a {StarterPok}!!"
        WriteFast(Congrats)
        print(StarterPok)
    else:
        WriteFast(ERROR)
        ChoseStarter()
except (ValueError, IndexError):
    # 覆盖输入非数字、索引越界两种错误
    WriteFast("输入无效,请重新选择!")
    ChoseStarter()

额外优化建议

  • 用YORN.lower() == "y"可以同时匹配大小写输入,比单独判断Y和y更简洁。
  • 打印时直接用StarterPok即可,无需再通过索引重复取值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 16:05:24