《Python核心编程》部分代码习题实践(持续更新)
第三章
3-10 交换异常处理方式
代码:
- #makeTextFile.py
- #!/usr/bin/env python
- 'makeTextFile.py'
- import os
- ls = os.linesep
- #get File name
- while True:
- fname = raw_input("Enter file name: ")
- try:
- fobj = open(fname,'w')
- except IOError, e:
- print "File open Failed"
- else:
- break;
- #get file contents lines
- all = []
- print "\nEnter lines('.' by itself to quit).\n"
- #loop until user terminate input
- while True:
- entry = raw_input('> ')
- if entry == '.':
- break
- else:
- all.append(entry)
- #write lines to file with proper line-ending
- #fobj = open(fname,'w')
- fobj.writelines(['%s%s' % (x,ls) for x in all])
- #fobj.write('\n',join(all))
- fobj.close()
- print "DONE"
- ######################################
- #readTextFile.py
- #!/usr/bin/env python
- 'readTextFile.py'
- import os
- #get filename
- fname = raw_input('Enter filename: ')
- #attempt to open file for reading
- if os.path.exists(fname):
- fobj = open(fname,'r')
- for eachLine in fobj:
- print eachLine,
- fobj.close()
3-11 移除逗号,用strip方法
代码:
- #!/usr/bin/env python
- 'readTextFile.py'
- import os
- #get filename
- fname = raw_input('Enter filename: ')
- #attempt to open file for reading
- if os.path.exists(fname):
- fobj = open(fname,'r')
- for eachLine in fobj:
- print eachLine.strip() #string.strip()
- fobj.close()
第五章习题:
- "chapter 5 's example"
- import random
- def countLevel(grade):
- "countLevel: input a grade,output its level"
- if grade > 100 or grade < 0:
- return 'Grade invalid!'
- elif 90 <= grade <= 100:
- return 'A'
- elif 80 <= grade < 90:
- return 'B'
- elif 70 <= grade < 80:
- return 'C'
- elif 60 <= grade < 70:
- return 'D'
- else:
- return 'E'
- def countAvg(gradelist):
- sumi = 0
- for i in gradelist:
- sumi += i
- return float(sumi)/len(gradelist)
- def matchStr(ka,kb):
- len1 = len(ka)
- len2 = len(kb)
- if len1 != len2:
- return False
- i = 0
- while i < len1:
- if ka[i] != kb[i]:
- return False
- i += 1
- return True
- def moneydiv(money):
- "There are 4 kinds of coins,input a num,output the minimum coins used to spell it"
- m1 = m5 = m10 = m25 = 0
- if money >= 25:
- m25 = money/25
- money -= m25*25
- if money >= 10:
- m10 = money/10
- money -= m10*10
- if money >= 5:
- m5 = money/5
- money -= m5*5
- if money >= 1:
- m1 = money
- return [m1,m5,m10,m25]
- def EvalInt3(expression):
- "input a expression,output it's consequence,only for int"
- length = len(expression)
- a = ""
- b = ""
- op = ""
- first = True
- tag = 0
- for i in range(0,length):
- if expression[i] != '+' and expression[i] != '-' and expression[i] != '*' and expression[i] != '/' and expression[i] != '%':
- if first:
- a += expression[i]
- else:
- b += expression[i]
- else:
- if expression[i] == '*' and expression[i-1] == '*':
- tag = 6
- first = False
- else:
- if expression[i] == '+':
- tag = 1
- elif expression[i] == '-':
- tag = 2
- elif expression[i] == '*':
- tag = 3
- elif expression[i] == '/':
- tag = 4
- elif expression[i] == '%':
- tag = 5
- first = False
- a = int(a)
- b = int(b)
- if tag == 1:
- return a+b
- elif tag == 2:
- return a-b
- elif tag == 3:
- return a*b
- elif tag == 4:
- return a/b
- elif tag == 5:
- return a%b
- elif tag == 6:
- return a**b
- def SquareArea(a):
- return a*a
- def CubeVolume(a):
- return a*a*a
- def CircleArea(r):
- return 3.14159*r*r
- def SphereVolume(r):
- return 4.0/3.0*3.14159*r*r*r
- def TempCtoF(c):
- return str(9.0/5.0*c + 32) + 'F'
- def TempFtoC(f):
- return str((f-32)*(5.0/9.0)) + 'C'
- def interest(ist):
- dayist = ist/365.0/100.0
- return ((1+dayist)**365 - 1.0)*100
- def GCD(a,b):
- "count gcd of two number"
- if b:
- return GCD(b,a%b)
- else:
- return a
- def RandomGO(N,n):
- a = []
- for i in range(0,N):
- k = random.randrange(0,n)
- a.append(k)
- b = []
- for i in range(0,N):
- ind = random.randrange(0,N)
- b.append(a[ind])
- sorted(b)
- return b
- def displayNumType(num):
- print num,'is',
- if isinstance(num,(int,long,float,complex)):
- print 'a number of type:',type(num).__name__
- else:
- print 'not a number at all!!'
第六-七章习题:
6-12
- #!/usr/bin/env python
- def findchr(string, char):
- i = 0
- for ch in string:
- if ch == char:
- return i
- i += 1
- return -1
- def rfindchr(string, char):
- i = len(string)-1
- while i >= 0:
- if(string[i] == char):
- return i
- i -= 1
- return -1
- def subchr(string, origchar, newchar):
- i = 0
- newstring = ""
- for ch in string:
- if ch == origchar:
- newstring += newchar
- continue
- newstring += ch
- return newstring
- print rfindchr('whatbeg','')
- print rfindchr('wahtbeg','b')
- print rfindchr('whahhhaaad','a')
- print subchr('whatbeg','w','t')
- #!/usr/bin/env python
- "Chapter 6"
- def num_to_str():
- num_str = raw_input('Enter a number: ')
- i = 0
- num_dic = {'':'zero','':'one','':'two','':'three','':'four','':'five','':'six','':'seven','':'eight','':'nine'}
- res = []
- while i < len(num_str):
- res.append(num_dic[num_str[i]])
- i += 1
- i = 0
- stri = ''
- while i < len(res)-1:
- stri += res[i] + '-'
- i += 1
- stri += res[i]
- print stri
- "Chapter 7"
- def Exchange_Key_Values(dict1):
- dict2 = {}
- for key in dict1:
- dict2[dict1[key]] = key
- return dict2
第八章:
- # -*- coding: cp936 -*-
- print '输入起始值: '
- num_str1 = raw_input()
- num1 = int(num_str1)
- print '输入结束值: '
- num_str2 = raw_input()
- num2 = int(num_str2)
- print 'DEC BIN OCT HEX ASCII'
- print '----------------------------------------'
- for i in range(num1,num2+1):
- print str(i) + ' ' + bin(i) + ' ' + oct(i) + ' ' + hex(i) + ' ' + chr(i)
第九章:
- #9-4
- f = open('1.txt','r')
- while True:
- for i in range(12):
- print f.readline()
- a = raw_input('Press any key to continue, "q" to quit: ')
- if a == 'q':
- break;
- else:
- continue
- #复制文件
- print 'Enter the two file name: '
- no1 = raw_input('From: ')
- no2 = raw_input('To: ')
- f1 = open(no1,'r')
- f2 = open(no2,'w')
- for eachLine in f1.readlines():
- f2.write(eachLine)
- f1.close()
- f2.close()
- print 'Done!'
- #9-18 搜索某个ASCII码对应的字符在文件中出现的次数
- name = raw_input('Enter the file name: ')
- char_num = raw_input('And the char_num: ')
- char_num_int = int(char_num)
- char = chr(char_num_int)
- f = open(name,'r')
- cnt = 0
- for eachLine in f.readlines():
- for i in eachLine:
- if char == i:
- cnt += 1
- f.close()
- print 'Done! COUNT is ' + str(cnt)
第11章:
爬取网页代码第一行和最后一行:
- #!/usr/bin/env python
- from urllib import urlretrieve
- def firstNonBlank(lines):
- for eachLine in lines:
- if not eachLine.strip():
- continue
- else:
- return eachLine
- def firstLast(webpage):
- f = open(webpage)
- lines = f.readlines()
- f.close()
- print firstNonBlank(lines)
- lines.reverse()
- print firstNonBlank(lines)
- def download(url = 'http://www.codeforces.com',process = firstLast):
- try:
- retval = urlretrieve(url)[0]
- except IOError:
- retval = None
- if retval:
- process(retval)
- if __name__ == '__main__':
- download('http://acm.uestc.edu.cn/#/')
测试函数:
- #!/usr/bin/env python
- def testit(func,*nkwargs,**kwargs):
- try:
- retval = func(*nkwargs,**kwargs)
- result = (True, retval)
- except Exception, diag:
- result = (False, str(diag))
- return result
- def test():
- funcs = (int, long, float)
- vals = (1234,12.34,'','12.34')
- for eachFunc in funcs:
- print '_'*20
- for eachVal in vals:
- retval = testit(eachFunc,eachVal)
- if retval[0]:
- print '%s(%s) = ' % (eachFunc.__name__,'eachVal'),retval[1]
- else:
- print '%s(%s) = FAILED: ' % (eachFunc.__name__,'eachVal'),retval[1]
- if __name__ == '__main__':
- test()
简单GUI例子
- from functools import partial
- import Tkinter
- root = Tkinter.Tk()
- MyButton = partial(Tkinter.Button,root,fg = 'white',bg = 'blue')
- b1 = MyButton(text = 'Button 1')
- b2 = MyButton(text = 'Button 2')
- qb = MyButton(text = 'QUIT',bg = 'red',command=root.quit)
- b1.pack()
- b2.pack()
- qb.pack(fill = Tkinter.X,expand = True)
- root.title('PFAs!')
- root.mainloop()
《Python核心编程》部分代码习题实践(持续更新)的更多相关文章
- python核心编程(第二版)习题
重新再看一遍python核心编程,把后面的习题都做一下.
- Python高级编程–正则表达式(习题)
原文:http://start2join.me/python-regex-answer-20141030/ ############################################## ...
- python核心编程第二版笔记
python核心编程第二版笔记由网友提供:open168 python核心编程--笔记(很详细,建议收藏) 解释器options:1.1 –d 提供调试输出1.2 –O 生成优化的字节码(生成 ...
- python核心编程--笔记
python核心编程--笔记 的解释器options: 1.1 –d 提供调试输出 1.2 –O 生成优化的字节码(生成.pyo文件) 1.3 –S 不导入site模块以在启动时查找pyt ...
- python核心编程--笔记(不定时跟新)(转)
的解释器options: 1.1 –d 提供调试输出 1.2 –O 生成优化的字节码(生成.pyo文件) 1.3 –S 不导入site模块以在启动时查找python路径 1.4 –v ...
- python核心编程笔记(转)
解释器options: 1.1 –d 提供调试输出 1.2 –O 生成优化的字节码(生成.pyo文件) 1.3 –S 不导入site模块以在启动时查找python路径 1.4 –v 冗 ...
- Python核心编程(第3版)PDF高清晰完整中文版|网盘链接附提取码下载|
一.书籍简介<Python核心编程(第3版)>是经典畅销图书<Python核心编程(第二版)>的全新升级版本.<Python核心编程(第3版)>总共分为3部分.第1 ...
- Python核心编程-闭包
百度搜了一下闭包的概念:简而言之,闭包的作用就是在外部函数执行完并返回后,闭包使得收机制不会收回函数所占用的资源,因为内部函数的执行需要依赖外函数中的变量.这是对闭包作用的非常直白的描述,不专业也不严 ...
- 学习《Python核心编程》做一下知识点提要,方便复习(一)
学习<Python核心编程>做一下知识点提要,方便复习. 计算机语言的本质是什么? a-z.A-Z.符号.数字等等组合成符合语法的字符串.供编译器.解释器翻译. 字母组合后产生各种变化拿p ...
随机推荐
- 从零开始,做一个NodeJS博客(一):Heroku上的最简NodeJS服务器
标签:NodeJS,Heroku 0 这里是这个伪系列的第一篇,因为我也不知道自己能不能做完,然后到底能做成什么样子.总之,尽力而为吧,加油. 1 Heroku App 的构成 Heroku 所谓的 ...
- Javascript数组算法和技巧总结
Js-arrayMethod https://github.com/HerbertKarajan/Js-arrayMethod List unique an array 数组去重 random str ...
- Emacs学习心得之 基础配置
作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 Emacs学习心得之 基础配置 1.前言2.基础配置 一.前言 本篇博文记录了Emacs的一 ...
- SharePoint 2010 网站备份还原简单介绍
今天尝试了SharePoint2010网站的备份和还原,从网上搜一些文档看看,然后自己试试,感觉和2007的操作没什么太大的区别,跟大家分享下自己尝试的命令行方式和数据库的方式,2007自己常用的也是 ...
- System.Security.Cryptography.CryptographicException: 指定了无效的提供程序类型
这两天在调用银联在线的支付接口,把银联提供的demo代码copy过来放到自己网站上,生成通过了,但是运行的时候就报错了: 指定了无效的提供程序类型. 说明: 执行当前 Web 请求期间,出现未经处理的 ...
- Android 短视频拍摄、拍照滤镜 第三方库SDK
视频 1.趣拍云服务 http://vcs.qupai.me/ 拍照 1.camera360 SDk 拍照滤镜 http://www.camera360.com/ 2 .凃图 http://tusdk ...
- XMPP框架的分析、导入及问题解决
上一篇讲了 XMPP调试与简单使用 ,本篇开始讲如何使用将XMPPFramework框架导入到项目中! 先来了解以下XMPPFramework都放了些什么: Authentication: 与登陆相关 ...
- 怎么查看Mac电脑的开机记录?
可以使用last命令查看Mac电脑来看开机记录,同时也能查看关机记录. 首先打开mac的命令终端: 命令行终端敲入命令:last | grep reboot (查看开机时间记录) 命令行终端敲入命令: ...
- 【代码笔记】iOS-改变导航条标题的颜色为红色
一,效果图. 二,代码. RootViewController.m - (void)viewDidLoad { [super viewDidLoad]; // Do any additional se ...
- 【代码笔记】iOS-UIScrollerView里有两个tableView
一,效果图. 二,工程图. 三,代码. RootViewController.h #import <UIKit/UIKit.h> @interface RootViewController ...