# 实验4# class MyError(Exception):# def __init__(self, string):# super().__init__()# self.string = string## def __str__(self):# if len(self.string) < 5: # 判断# return 'The input is of length 3,expecting at least 5'# else:# return 'success'### try:# raise MyError(input('input:')) # 手动引发异常# except MyError as error: # 捕获,异常信息为error# print(error) # 打印# # 实验5# class IllegalArgumentException(Exception):# def __init__(self, sides:list):# super().__init__()# self.sides = sides## def is_tangle(self):# max_side = max(self.sides[0], self.sides[1], self.sides[2]) # 找到最大边# ls_sides = list(self.sides)# ls_sides.remove(max_side) # 将剩余的较小两边放入列表# if ls_sides[0]+ls_sides[1] > max_side: # 判断较小两边之和是否大于第三边# return True## def __str__(self):# if not self.is_tangle():# return 'a,b,c不能构成三角形'# else:# return str(sum(self.sides))### class IllegalArgLenException(Exception):# def __init__(self):# super().__init__()## def __str__(self):# return '参数个数不正确'### # sides = list([1, 2]) ##IllegalArgLenException 异常# # sides = list(['a', 'b', 'c']) ##TypeError 异常# # sides = list([1, 2, 3]) ##IllegalArgumentException 异常# # sides = list([3, 4, 5])## try:# for i in sides:# if not isinstance(i, int or float): # 输入是否为数字# raise TypeError# if len(sides) != 3: # 参数个数是否为3# raise IllegalArgLenException# else:# raise IllegalArgumentException(sides)## except TypeError:# print('请输入数字类型')# except IllegalArgLenException as error1:# print(error1)# except IllegalArgumentException as error2:# print(error2)## finally:# print('程序运行结束')# # 实验6# try:# score = int(input('input:'))# assert 0 <= score <= 100, "非法输入!" # 满足断言条件,引发AssertionError异常# if score >= 90:# print('score:A')# elif 80 <= score <= 89:# print('score:B')# elif 60 <= score <= 79:# print('score:C')# else:# print('score:D')# except AssertionError as error:# print(error)
嗯嗯嗯嗯嗯
最新推荐文章于 2024-07-18 15:53:23 发布