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

Python如何处理作为函数参数的用户输入触发的ValueError异常

解决方案

问题根源

你将int(input("Are you configuring a (1)962, (2)Audience, or (3)mAP? "))直接作为参数传入configselect时,整数转换操作会在函数调用前先执行,一旦输入非整数内容,int()转换会直接抛出ValueError,程序还没进入configselect逻辑就崩溃了,所以确实没法在现有configselect函数里直接捕获这个异常。

修改后的实现代码

def configselect(choice):
    if choice == 1:
        print("you chose 962")
    elif choice == 2:
        print("you chose Audience")
    elif choice == 3:
        print("you chose mAP")
    else:
        print('Thats not a valid Number. Please try Again.')
        # 触发重试
        get_input_and_select()

def get_input_and_select():
    while True:
        try:
            user_input = int(input("Are you configuring a (1)962, (2)Audience, or (3)mAP? "))
            break
        except ValueError:
            print("Sorry thats not right, try again")
    configselect(user_input)

# 启动输入流程
get_input_and_select()

逻辑说明

  • 新增get_input_and_select函数专门处理用户输入、类型校验和重试逻辑
  • 用try-except块捕获int()转换时抛出的ValueError,匹配你输入字符串、浮点值的异常捕获需求,触发指定提示后自动重试
  • 类型校验通过后再调用configselect处理业务逻辑,输入不在1-3范围内的整数也会触发重试

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 20:00:04