Python异常处理——try...except、主动引发异常(raise)、断言(assert)
来源:互联网 发布:sublime text python 编辑:程序博客网 时间:2024/05/29 03:29
Python习题十
一、 编写函数devide(x, y),x为被除数,y为除数。要求考虑异常情况的处理。
1、 被零除时,输出”division by zero! “;
2、 类型不一致时,强制转换为整数再调用本函数;
3、 若没有上述异常则输出计算结果。
源代码:
class DTError(Exception): #感觉不写也可以呀 但是没有这个类定义 下面的DTError就会报错 passdef devide(x,y): try: ans=x/y if(type(x)!=type(y)): #如果两个数类型不同,抛出异常 raise DTError except ZeroDivisionError: #抛出除数为0的异常 return 'division by zero!' except DTError: #类型不同的异常 print ('The two nums have differet type') #先提示类型不同 x=int(x) #将x,y强制转换成int,再次调用函数。本来在这个位置嵌套了一个捕捉异常,后来发现没有必要,就删除了 y=int(y) devide(x,y) return ans except: return 'other problems, angry' #对 我很气 else: return ans
运行结果:
二、 编写函数test(password, earning, age)用于检测输入错误。要求输入密码password第一个符号不能是数字,工资earnings的范围是0—20000,工作年龄的范围是18—70。使用断言来实现检查,若三项检查都通过则返回True。
def test(password, earning, age): #assert 1<0 assert password[0] not in ['0','1','2','3','4','5','6','7','8','9'] assert int(earning)>=0 and int(earning)<=20000 assert int(age)>=18 and int(age)<=70 return True
运行结果:
阅读全文
0 0
- Python异常处理——try...except、主动引发异常(raise)、断言(assert)
- 【python学习笔记】Python异常处理raise、try...except、断言assert
- Python异常处理try...except...finally raise assert
- (Python)异常处理try...except、raise
- (Python)异常处理try...except、raise
- Python异常处理try...except、raise
- Python---异常处理try...except、raise
- (Python)异常处理try...except、raise
- Python异常处理try...except、raise
- 异常处理try...except、raise
- 异常 断言 try except finally assert
- python中的异常处理try/except/finally/raise
- 异常处理try/raise/assert/with
- python 引发异常 raise()及异常处理
- Python--小甲鱼学习笔记--第33课:异常处理(try-except, try-finally, raise)
- Python 异常处理 try/except
- python异常处理try...except
- try块和异常处理,断言assert
- 参数timeout--防止URL不可访问
- web前端优化(2)
- MySQL ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)解决办法
- 11.13学习心得
- 彻底剖析numpy的array对象
- Python异常处理——try...except、主动引发异常(raise)、断言(assert)
- Python简介,发展历史及特点
- 简单死锁案例
- 数据结构与算法分析(Java语言描述)(19)—— 二叉搜索树删除指定的节点
- 《二叉树的遍历》
- web前端优化(3)
- git 常用命令
- 运行QT工程时显示控制台
- 面向对象 封装 private关键字 构造方法