《Python核心编程》第10章 习题
来源:互联网 发布:淘宝pc端 编辑:程序博客网 时间:2024/06/05 09:11
10–6. 改进的 open().
为内建的 open() 函数创建一个封装. 使得成功打开文件后, 返回文件句柄; 若打开失败则返回给调用者 None , 而不是生成一个异常. 这样你打开文件时就不需要额外的异常处理语句
def myopen(infile,mode='r'): try: fo=open(infile,mode) except IOError: fo=None return foif __name__ == '__main__': f = myopen('1.txt') print f
本章的开头, 我们给出了一个"安全"的 float() 函数,它建立在内建函数 float() 上, 可以检测并处理 float() 可能会引发的两种不同异常. 同样,raw_input() 函数也可能会生成两种异常, EOFError (文件末尾 EOF, 在 Unix 下是由于按下了Ctrl+D 在 Dos 下是因为 Ctrl+Z) 或是 KeyboardInterrupt ( 取消输入, 一般是由于按下了Ctrl+C). 请创建一个封装函数 safe_input() , 在发生异常时返回 None
def safe_input(inputstr): try: instr=raw_input(inputstr) except (EOFError,KeyboardInterrupt): instr=None return instrif __name__ == '__main__': s = safe_input('pls input something:') print s
10–9. 改进的 math.sqrt().
math 模块包含大量用于处理数值相关运算的函数和常量. 不幸的是, 它不能识别复数, 所以我们创建了 cmath 模块来支持复数相关运算. 请创建一个safe_sqrt() 函数, 它封装 math.sqrt() 并能处理负值, 返回一个对应的复数.
import cmath,mathdef safe_sqrt(x): try: num=math.sqrt(x) except ValueError: num=cmath.sqrt(x) return numif __name__ == '__main__': x = float(raw_input('pls input a number:')) s = safe_sqrt(x) print s
0 0
- 《Python核心编程》第10章 习题
- 《Python核心编程》第2章 习题
- 《Python核心编程》第3章 习题
- 《Python核心编程》第5章 习题
- 《Python核心编程》第6章 习题
- 《Python核心编程》第7章 习题
- 《Python核心编程》第8章 习题
- 《Python核心编程》第9章 习题
- 《Python核心编程》第11章 习题
- 《Python核心编程》第12章 习题
- 《Python核心编程》第6章 习题
- 《Python核心编程》第7章 习题
- 《Python核心编程》第13章 习题
- 《Python核心编程》第7章 习题
- 《Python核心编程》第9章 习题
- 《Python核心编程》第12章 习题
- 《Python核心编程》第14章 习题
- python核心编程第12章习题
- C#与Java的时间转换
- ubuntu 开机出错disk by-uuid ########### does not exist dropping to a shell
- 设置SOCKET的发送与接收缓冲区
- wamp配置多目录访问方法
- Effective C++读书笔记
- 《Python核心编程》第10章 习题
- 关于socket buffer size的调优
- POJ 1753 枚举
- 中文知识图谱构建方法研究3
- iOS中得block代码块的定义及使用
- 1137. 河床
- XML/JSON 后台数据
- mac android studio please check subversion ssl setting
- HDU 过山车(二分匹配)