第三章

3-10 交换异常处理方式

代码:

  1. #makeTextFile.py
  2.  
  3. #!/usr/bin/env python
  4.  
  5. 'makeTextFile.py'
  6. import os
  7. ls = os.linesep
  8.  
  9. #get File name
  10.  
  11. while True:
  12. fname = raw_input("Enter file name: ")
  13. try:
  14. fobj = open(fname,'w')
  15. except IOError, e:
  16. print "File open Failed"
  17. else:
  18. break;
  19.  
  20. #get file contents lines
  21.  
  22. all = []
  23. print "\nEnter lines('.' by itself to quit).\n"
  24.  
  25. #loop until user terminate input
  26.  
  27. while True:
  28. entry = raw_input('> ')
  29. if entry == '.':
  30. break
  31. else:
  32. all.append(entry)
  33.  
  34. #write lines to file with proper line-ending
  35. #fobj = open(fname,'w')
  36. fobj.writelines(['%s%s' % (x,ls) for x in all])
  37. #fobj.write('\n',join(all))
  38. fobj.close()
  39. print "DONE"
  40.  
  41. ######################################
  42.  
  43. #readTextFile.py
  44.  
  45. #!/usr/bin/env python
  46.  
  47. 'readTextFile.py'
  48. import os
  49.  
  50. #get filename
  51. fname = raw_input('Enter filename: ')
  52. print
  53.  
  54. #attempt to open file for reading
  55.  
  56. if os.path.exists(fname):
  57. fobj = open(fname,'r')
  58. for eachLine in fobj:
  59. print eachLine,
  60.  
  61. fobj.close()

3-11 移除逗号,用strip方法

代码:

  1. #!/usr/bin/env python
  2.  
  3. 'readTextFile.py'
  4. import os
  5.  
  6. #get filename
  7. fname = raw_input('Enter filename: ')
  8. print
  9.  
  10. #attempt to open file for reading
  11.  
  12. if os.path.exists(fname):
  13. fobj = open(fname,'r')
  14. for eachLine in fobj:
  15. print eachLine.strip() #string.strip()
  16.  
  17. fobj.close()

第五章习题:

  1. "chapter 5 's example"
  2. import random
  3.  
  4. def countLevel(grade):
  5. "countLevel: input a grade,output its level"
  6. if grade > 100 or grade < 0:
  7. return 'Grade invalid!'
  8. elif 90 <= grade <= 100:
  9. return 'A'
  10. elif 80 <= grade < 90:
  11. return 'B'
  12. elif 70 <= grade < 80:
  13. return 'C'
  14. elif 60 <= grade < 70:
  15. return 'D'
  16. else:
  17. return 'E'
  18.  
  19. def countAvg(gradelist):
  20. sumi = 0
  21. for i in gradelist:
  22. sumi += i
  23. return float(sumi)/len(gradelist)
  24.  
  25. def matchStr(ka,kb):
  26. len1 = len(ka)
  27. len2 = len(kb)
  28. if len1 != len2:
  29. return False
  30. i = 0
  31. while i < len1:
  32. if ka[i] != kb[i]:
  33. return False
  34. i += 1
  35. return True
  36.  
  37. def moneydiv(money):
  38. "There are 4 kinds of coins,input a num,output the minimum coins used to spell it"
  39. m1 = m5 = m10 = m25 = 0
  40. if money >= 25:
  41. m25 = money/25
  42. money -= m25*25
  43. if money >= 10:
  44. m10 = money/10
  45. money -= m10*10
  46. if money >= 5:
  47. m5 = money/5
  48. money -= m5*5
  49. if money >= 1:
  50. m1 = money
  51. return [m1,m5,m10,m25]
  52.  
  53. def EvalInt3(expression):
  54. "input a expression,output it's consequence,only for int"
  55. length = len(expression)
  56. a = ""
  57. b = ""
  58. op = ""
  59. first = True
  60. tag = 0
  61. for i in range(0,length):
  62. if expression[i] != '+' and expression[i] != '-' and expression[i] != '*' and expression[i] != '/' and expression[i] != '%':
  63. if first:
  64. a += expression[i]
  65. else:
  66. b += expression[i]
  67. else:
  68. if expression[i] == '*' and expression[i-1] == '*':
  69. tag = 6
  70. first = False
  71. else:
  72. if expression[i] == '+':
  73. tag = 1
  74. elif expression[i] == '-':
  75. tag = 2
  76. elif expression[i] == '*':
  77. tag = 3
  78. elif expression[i] == '/':
  79. tag = 4
  80. elif expression[i] == '%':
  81. tag = 5
  82. first = False
  83. a = int(a)
  84. b = int(b)
  85. if tag == 1:
  86. return a+b
  87. elif tag == 2:
  88. return a-b
  89. elif tag == 3:
  90. return a*b
  91. elif tag == 4:
  92. return a/b
  93. elif tag == 5:
  94. return a%b
  95. elif tag == 6:
  96. return a**b
  97.  
  98. def SquareArea(a):
  99. return a*a
  100.  
  101. def CubeVolume(a):
  102. return a*a*a
  103.  
  104. def CircleArea(r):
  105. return 3.14159*r*r
  106.  
  107. def SphereVolume(r):
  108. return 4.0/3.0*3.14159*r*r*r
  109.  
  110. def TempCtoF(c):
  111. return str(9.0/5.0*c + 32) + 'F'
  112.  
  113. def TempFtoC(f):
  114. return str((f-32)*(5.0/9.0)) + 'C'
  115.  
  116. def interest(ist):
  117. dayist = ist/365.0/100.0
  118. return ((1+dayist)**365 - 1.0)*100
  119.  
  120. def GCD(a,b):
  121. "count gcd of two number"
  122. if b:
  123. return GCD(b,a%b)
  124. else:
  125. return a
  126.  
  127. def RandomGO(N,n):
  128. a = []
  129. for i in range(0,N):
  130. k = random.randrange(0,n)
  131. a.append(k)
  132. b = []
  133. for i in range(0,N):
  134. ind = random.randrange(0,N)
  135. b.append(a[ind])
  136. sorted(b)
  137. return b
  138.  
  139. def displayNumType(num):
  140. print num,'is',
  141. if isinstance(num,(int,long,float,complex)):
  142. print 'a number of type:',type(num).__name__
  143. else:
  144. print 'not a number at all!!'

第六-七章习题:

6-12

  1. #!/usr/bin/env python
  2.  
  3. def findchr(string, char):
  4. i = 0
  5. for ch in string:
  6. if ch == char:
  7. return i
  8. i += 1
  9. return -1
  10.  
  11. def rfindchr(string, char):
  12. i = len(string)-1
  13. while i >= 0:
  14. if(string[i] == char):
  15. return i
  16. i -= 1
  17. return -1
  18.  
  19. def subchr(string, origchar, newchar):
  20. i = 0
  21. newstring = ""
  22. for ch in string:
  23. if ch == origchar:
  24. newstring += newchar
  25. continue
  26. newstring += ch
  27. return newstring
  28.  
  29. print rfindchr('whatbeg','')
  30. print rfindchr('wahtbeg','b')
  31. print rfindchr('whahhhaaad','a')
  32. print subchr('whatbeg','w','t')
  1. #!/usr/bin/env python
  2.  
  3. "Chapter 6"
  4.  
  5. def num_to_str():
  6. num_str = raw_input('Enter a number: ')
  7.  
  8. i = 0
  9.  
  10. num_dic = {'':'zero','':'one','':'two','':'three','':'four','':'five','':'six','':'seven','':'eight','':'nine'}
  11. res = []
  12.  
  13. while i < len(num_str):
  14. res.append(num_dic[num_str[i]])
  15. i += 1
  16.  
  17. i = 0
  18. stri = ''
  19.  
  20. while i < len(res)-1:
  21. stri += res[i] + '-'
  22. i += 1
  23.  
  24. stri += res[i]
  25.  
  26. print stri
  27.  
  28. "Chapter 7"
  29.  
  30. def Exchange_Key_Values(dict1):
  31. dict2 = {}
  32. for key in dict1:
  33. dict2[dict1[key]] = key
  34.  
  35. return dict2

第八章:

  1. # -*- coding: cp936 -*-
  2.  
  3. print '输入起始值: '
  4. num_str1 = raw_input()
  5. num1 = int(num_str1)
  6. print '输入结束值: '
  7. num_str2 = raw_input()
  8. num2 = int(num_str2)
  9.  
  10. print 'DEC BIN OCT HEX ASCII'
  11. print '----------------------------------------'
  12.  
  13. for i in range(num1,num2+1):
  14. print str(i) + ' ' + bin(i) + ' ' + oct(i) + ' ' + hex(i) + ' ' + chr(i)

第九章:

  1. #9-4
  2. f = open('1.txt','r')
  3.  
  4. while True:
  5. for i in range(12):
  6. print f.readline()
  7. a = raw_input('Press any key to continue, "q" to quit: ')
  8. if a == 'q':
  9. break;
  10. else:
  11. continue
  1. #复制文件
  2. print 'Enter the two file name: '
  3. no1 = raw_input('From: ')
  4. no2 = raw_input('To: ')
  5.  
  6. f1 = open(no1,'r')
  7. f2 = open(no2,'w')
  8.  
  9. for eachLine in f1.readlines():
  10. f2.write(eachLine)
  11.  
  12. f1.close()
  13. f2.close()
  14.  
  15. print 'Done!'
  1. #9-18 搜索某个ASCII码对应的字符在文件中出现的次数
  2. name = raw_input('Enter the file name: ')
  3. char_num = raw_input('And the char_num: ')
  4. char_num_int = int(char_num)
  5. char = chr(char_num_int)
  6.  
  7. f = open(name,'r')
  8.  
  9. cnt = 0
  10.  
  11. for eachLine in f.readlines():
  12. for i in eachLine:
  13. if char == i:
  14. cnt += 1
  15.  
  16. f.close()
  17.  
  18. print 'Done! COUNT is ' + str(cnt)

第11章:

爬取网页代码第一行和最后一行:

  1. #!/usr/bin/env python
  2.  
  3. from urllib import urlretrieve
  4.  
  5. def firstNonBlank(lines):
  6. for eachLine in lines:
  7. if not eachLine.strip():
  8. continue
  9. else:
  10. return eachLine
  11.  
  12. def firstLast(webpage):
  13. f = open(webpage)
  14. lines = f.readlines()
  15. f.close()
  16. print firstNonBlank(lines)
  17. lines.reverse()
  18. print firstNonBlank(lines)
  19.  
  20. def download(url = 'http://www.codeforces.com',process = firstLast):
  21. try:
  22. retval = urlretrieve(url)[0]
  23. except IOError:
  24. retval = None
  25. if retval:
  26. process(retval)
  27.  
  28. if __name__ == '__main__':
  29. download('http://acm.uestc.edu.cn/#/')

测试函数:

  1. #!/usr/bin/env python
  2.  
  3. def testit(func,*nkwargs,**kwargs):
  4. try:
  5. retval = func(*nkwargs,**kwargs)
  6. result = (True, retval)
  7. except Exception, diag:
  8. result = (False, str(diag))
  9. return result
  10.  
  11. def test():
  12. funcs = (int, long, float)
  13. vals = (1234,12.34,'','12.34')
  14. for eachFunc in funcs:
  15. print '_'*20
  16. for eachVal in vals:
  17. retval = testit(eachFunc,eachVal)
  18. if retval[0]:
  19. print '%s(%s) = ' % (eachFunc.__name__,'eachVal'),retval[1]
  20. else:
  21. print '%s(%s) = FAILED: ' % (eachFunc.__name__,'eachVal'),retval[1]
  22.  
  23. if __name__ == '__main__':
  24. test()

简单GUI例子

  1. from functools import partial
  2. import Tkinter
  3.  
  4. root = Tkinter.Tk()
  5. MyButton = partial(Tkinter.Button,root,fg = 'white',bg = 'blue')
  6. b1 = MyButton(text = 'Button 1')
  7. b2 = MyButton(text = 'Button 2')
  8.  
  9. qb = MyButton(text = 'QUIT',bg = 'red',command=root.quit)
  10.  
  11. b1.pack()
  12. b2.pack()
  13.  
  14. qb.pack(fill = Tkinter.X,expand = True)
  15. root.title('PFAs!')
  16. root.mainloop()

《Python核心编程》部分代码习题实践(持续更新)的更多相关文章

  1. python核心编程(第二版)习题

    重新再看一遍python核心编程,把后面的习题都做一下.

  2. Python高级编程–正则表达式(习题)

    原文:http://start2join.me/python-regex-answer-20141030/ ############################################## ...

  3. python核心编程第二版笔记

    python核心编程第二版笔记由网友提供:open168 python核心编程--笔记(很详细,建议收藏) 解释器options:1.1 –d   提供调试输出1.2 –O   生成优化的字节码(生成 ...

  4. python核心编程--笔记

    python核心编程--笔记 的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找pyt ...

  5. python核心编程--笔记(不定时跟新)(转)

    的解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找python路径 1.4 –v   ...

  6. python核心编程笔记(转)

    解释器options: 1.1 –d   提供调试输出 1.2 –O   生成优化的字节码(生成.pyo文件) 1.3 –S   不导入site模块以在启动时查找python路径 1.4 –v   冗 ...

  7. Python核心编程(第3版)PDF高清晰完整中文版|网盘链接附提取码下载|

    一.书籍简介<Python核心编程(第3版)>是经典畅销图书<Python核心编程(第二版)>的全新升级版本.<Python核心编程(第3版)>总共分为3部分.第1 ...

  8. Python核心编程-闭包

    百度搜了一下闭包的概念:简而言之,闭包的作用就是在外部函数执行完并返回后,闭包使得收机制不会收回函数所占用的资源,因为内部函数的执行需要依赖外函数中的变量.这是对闭包作用的非常直白的描述,不专业也不严 ...

  9. 学习《Python核心编程》做一下知识点提要,方便复习(一)

    学习<Python核心编程>做一下知识点提要,方便复习. 计算机语言的本质是什么? a-z.A-Z.符号.数字等等组合成符合语法的字符串.供编译器.解释器翻译. 字母组合后产生各种变化拿p ...

随机推荐

  1. 从零开始,做一个NodeJS博客(一):Heroku上的最简NodeJS服务器

    标签:NodeJS,Heroku 0 这里是这个伪系列的第一篇,因为我也不知道自己能不能做完,然后到底能做成什么样子.总之,尽力而为吧,加油. 1 Heroku App 的构成 Heroku 所谓的 ...

  2. Javascript数组算法和技巧总结

    Js-arrayMethod https://github.com/HerbertKarajan/Js-arrayMethod List unique an array 数组去重 random str ...

  3. Emacs学习心得之 基础配置

    作者:枫雪庭 出处:http://www.cnblogs.com/FengXueTing-px/ 欢迎转载 Emacs学习心得之 基础配置 1.前言2.基础配置 一.前言 本篇博文记录了Emacs的一 ...

  4. SharePoint 2010 网站备份还原简单介绍

    今天尝试了SharePoint2010网站的备份和还原,从网上搜一些文档看看,然后自己试试,感觉和2007的操作没什么太大的区别,跟大家分享下自己尝试的命令行方式和数据库的方式,2007自己常用的也是 ...

  5. System.Security.Cryptography.CryptographicException: 指定了无效的提供程序类型

    这两天在调用银联在线的支付接口,把银联提供的demo代码copy过来放到自己网站上,生成通过了,但是运行的时候就报错了: 指定了无效的提供程序类型. 说明: 执行当前 Web 请求期间,出现未经处理的 ...

  6. Android 短视频拍摄、拍照滤镜 第三方库SDK

    视频 1.趣拍云服务 http://vcs.qupai.me/ 拍照 1.camera360 SDk 拍照滤镜 http://www.camera360.com/ 2 .凃图 http://tusdk ...

  7. XMPP框架的分析、导入及问题解决

    上一篇讲了 XMPP调试与简单使用 ,本篇开始讲如何使用将XMPPFramework框架导入到项目中! 先来了解以下XMPPFramework都放了些什么: Authentication: 与登陆相关 ...

  8. 怎么查看Mac电脑的开机记录?

    可以使用last命令查看Mac电脑来看开机记录,同时也能查看关机记录. 首先打开mac的命令终端: 命令行终端敲入命令:last | grep reboot (查看开机时间记录) 命令行终端敲入命令: ...

  9. 【代码笔记】iOS-改变导航条标题的颜色为红色

    一,效果图. 二,代码. RootViewController.m - (void)viewDidLoad { [super viewDidLoad]; // Do any additional se ...

  10. 【代码笔记】iOS-UIScrollerView里有两个tableView

    一,效果图. 二,工程图. 三,代码. RootViewController.h #import <UIKit/UIKit.h> @interface RootViewController ...