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

Python3中用字典模拟switch语句时输入错误无法弹出自定义提示怎么办

问题原因

你的代码报错发生在x = int(input())执行阶段,还没走到后续的字典匹配逻辑。当用户输入非数字内容时,int()类型转换会直接抛出ValueError异常,程序直接中断,自然不会触发你预设的default错误提示分支。

修复方案

有两种常用的实现方式,你可以按需选择:

方案1:添加异常捕获逻辑

在输入转换位置套try-except块,捕获转换失败的场景,直接触发错误提示:

def switch():
    try:
        x = int(input())
    except ValueError:
        # 输入非数字时直接输出错误提示
        print("Error. Please enter the number that represents the activity that the participant would like to do. Only enter one of the following: 1,2,3,4,5,6")
        return
    
    # 后续原有逻辑保持不变即可
    def cookies(): 
      replit.clear()
      second.Registration()
      informationScout()
      print("Activity chosen: Bake and sell cookies\n")
      second.Continue()

    def bracelets():
      replit.clear()
      second.Registration()
      informationScout()
      print("Activity chosen: Make survival bracelets\n")
      second.Continue()

    def hike():
      replit.clear()
      second.Registration()
      informationScout()
      print("Activity chosen: Night time hike\n")
      second.Continue()

    def swimming():
      replit.clear()
      second.Registration()
      informationScout()
      print("Activity chosen: Swimming\n")
      second.Continue()

    def handicraft():
      replit.clear()
      second.Registration()
      informationScout()
      print("Activity chosen: Handicraft with wood\n")
      second.Continue()

    def ownProposal():
      replit.clear()
      second.Registration()
      informationScout()
      print("Activity chosen: Own proposal\n")
      second.Continue()

    def default():
      print("Error. Please enter the number that represents the activity that the participant would like to do. Only enter one of the following: 1,2,3,4,5,6")

    # 注意:不要用dict作为变量名,这是Python内置字典类型的关键字,重名会覆盖原生功能
    activity_map = {
      1: cookies,
      2: bracelets,
      3: hike,
      4: swimming,
      5: handicraft,
      6: ownProposal
    }

    activity_map.get(x, default)()
switch()

方案2:提前校验输入格式

先把输入存为字符串,校验为合法数字后再做类型转换,避免异常抛出:

def switch():
    input_str = input().strip()
    # 先判断输入是否为纯数字
    if not input_str.isdigit():
        print("Error. Please enter the number that represents the activity that the participant would like to do. Only enter one of the following: 1,2,3,4,5,6")
        return
    x = int(input_str)
    # 后续原有逻辑保持不变即可
额外注意事项

你原有代码中定义字典时用了dict作为变量名,这是Python内置类型的保留关键字,建议替换为自定义名称比如activity_map,避免覆盖原生字典功能。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 09:24:04