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
相关产品推荐
相关产品推荐

