Python try-except函数异常排查:无效时间格式未触发错误
看起来你遇到的问题根源在于两个地方:is_time_format函数的逻辑错误,以及something_to_military里try-except块的使用方式不对。让我逐一拆解:
1. is_time_format函数的关键错误
你的is_time_format里有几个致命的逻辑问题,导致它无法正确识别像"2:45 AMX"这种无效后缀的情况:
错误1:方法调用未加括号
你写了x.isalpha == False和y.isalpha == False,这里的isalpha是字符串方法,必须调用它(即x.isalpha())才能得到布尔值。直接写x.isalpha得到的是方法对象本身,永远不会等于False,所以这两个判断完全不起作用。
错误2:判断逻辑完全颠倒
就算你加上了括号,x.isalpha() == False的判断逻辑也是反的——我们需要确保x(冒号前的小时部分)是数字,不是字母,所以应该判断x.isalpha()为True时返回False,或者直接判断x.isdigit()是否为False(你后面已经有这个判断了,前面这两个isalpha的判断完全多余且错误)。
错误3:未处理无空格的情况
如果输入字符串没有空格(比如"2:45PM"),s.find(' ')会返回-1,此时s[pos2+1:]会变成s[0:](整个字符串),而y = s[pos1+1:pos2]会变成s[pos1+1:-1],这可能导致后续判断出错。你需要先检查pos2是否为-1,如果是直接返回False。
错误4:类型判断不严谨
type(s)!=type('str')的写法不够优雅,而且无法处理字符串子类的情况,应该用isinstance(s, str)来判断是否为字符串类型。
修复后的is_time_format函数
def is_time_format(s): """Returns: True if s is a string in 12-hour format with AM/PM Example: is_time_format('2:45 PM') returns True is_time_format('2:45PM') returns False is_time_format('14:45') returns False is_time_format('14:45 AM') returns False is_time_format(245) returns False Parameter s: the candidate time to format Precondition: NONE (s can be any value)""" # 先判断是否为字符串 if not isinstance(s, str): return False pos1 = s.find(':') pos2 = s.find(' ') # 检查是否有且仅有一个冒号,以及必须有空格分隔时间和后缀 if s.count(':') != 1 or pos2 == -1: return False x = s[:pos1] y = s[pos1+1:pos2] suff = s[pos2+1:] # 检查小时和分钟部分是否为数字 if not x.isdigit() or not y.isdigit(): return False # 检查小时和分钟的长度与范围 if len(x) >=3 or len(y)>=3: return False hour = int(x) minute = int(y) if hour >12 or hour <1 or minute >=60 or minute <0: return False # 检查后缀是否为AM或PM if suff not in ('AM', 'PM'): return False return True
2. something_to_military函数的逻辑错误
你的try块里写了is_time_format(s) == True,但这个表达式只是计算了一个布尔值,没有任何实际作用——不管结果是True还是False,代码都会继续执行return time_to_military(s)。只有当time_to_military抛出异常时,才会进入except块,但如果time_to_military没有对无效参数做校验,就会返回错误的结果。
根据题目要求(不能用if,只能用try-except),你应该用assert来触发异常:当is_time_format(s)返回False时,assert会抛出AssertionError,从而进入except块返回错误信息。
修复后的something_to_military函数
def something_to_military(s): """Returns: the time in 24-hour (military) format if appropriate. The function is the same as time_to_military if s satisfies the precondition for that function. If s does not satisfy the precondition then this function returns 'Invalid time format' Examples: something_to_military('2:45 PM') returns '14:45' something_to_military('9:05 AM') returns '09:05' something_to_military('12:00 AM') returns '00:00' something_to_military(905) returns 'Invalid time format' something_to_military('abc') returns 'Invalid time format' something_to_military('9:05') returns 'Invalid time format' Parameter s: the candidate time to format Precondition: NONE (s can be any value)""" # You are not allowed to use 'if' in this definition. Use try-except instead. # Hint: You have to complete PART 2 before you complete this part. try: assert is_time_format(s), "Invalid time format" return time_to_military(s) except: return 'Invalid Time Format'
这样修改后,当你传入"2:45 AMX"时,is_time_format会返回False,触发assert异常,进入except块返回正确的错误信息。
内容的提问来源于stack exchange,提问作者CornellCoder

