当前位置:首页 >> 理学 >>

Python核心编程第二版-习题答案


Chun_AppA.fm Page 1011 Wednesday, August 23, 2006 5:19 PM

Answers to Selected Exercises
Chapter 2
5. Loops and numbers
a)
i = 0 while i < 11: i += 1

b)
for i in range(11): pass

6. Conditionals
n = int(raw_input('enter a number: ')) if n < 0: print 'negative' elif n > 0: print 'positive' else: print 'zero'

1011

Chun_AppA.fm Page 1012 Wednesday, August 23, 2006 5:19 PM

1012

Appendix A

7. Loops and strings
s = raw_input('enter a string: ') for eachChar in s: print eachChar # (does not print index)

or
for i in range(len(s)): print i, s[i]

or
i = 0 slen = len(s) while i < slen: print i, s[i]

or
for i, x in enumerate(s): print i, x

8. Loops and operators
subtot = 0 for i in range(5): subtot += int(raw_input('enter a number: ')) print subtot

or
# uses sum() BIF and generator expressions print sum(int(raw_input('enter a number: ')) for i in range(5))

Chapter 3
4. Statements
Use ;

5. Statements
Use \ (unless part of a comma-separated sequence in which case \ is optional)

7. Identiers
40XL $saving$ print 0x40L big-daddy 2hot2touch thisIsn'tAVar if counter-1 number symbol keyword number symbol number symbol keyword symbol

Chun_AppA.fm Page 1013 Wednesday, August 23, 2006 5:19 PM

Answers to Selected Exercises

1013

Chapter 4
1. Python objects
All Python objects have three attributes: type, ID, and value. All are readonly with a possible exception of the value (which can be changed only if the object is mutable).

5. str() vs. repr()
repr() is a built-in function while str() was a built-in function that changed to a factory function in Python 2.2. They will both return a string representation of an object; however, str() returns a printable string representation while repr() (and the backquote operator '') return an evaluatable string representation of an object, meaning that it is a string that represents a (valid) Python object that would be created if passed to eval().

6. Object equality
type(a) == type(b) whether the value of type(a) is the same as the value of type(b)... == is a value compare type(a) is type(b) whether the type objects returned by type(a) and type(b) are the same object Since there exists only one (type) object for each built-in type, there is no need to check their values; hence, only the latter form should be used.

Chapter 5
8. Geometry
import math def sqcube(): s = float(raw_input('enter length of one side: ')) print 'the area is:', s ** 2., '(units squared)' print 'the volume is:', s ** 3., '(cubic units)' def cirsph(): r = float(raw_input('enter length of radius: ')) print 'the area is:', math.pi * (r ** 2.), '(units squared)' print 'the volume is:', (4. / 3.) * math.pi * (r ** 3.), '(cubic units)' sqcube() cirsph()

Chun_AppA.fm Page 1014 Wednesday, August 23, 2006 5:19 PM

1014

Appendix A

11. Modulus
a)
for i in range(0, 22, 2): print i # range(0, 21, 2) okay too

or
for i in range(22): if i % 2 == 0: print i # range(21) okay too

b)
for i in range(1, 20, 2): print i # range(1, 21, 2) okay too

or
for i in range(20): if i % 2 != 0: print i # range(21) okay too

c) When i % 2 == 0, it's even (divisible by 2), otherwise it's odd.

Chapter 6
1. Strings
find(), rfind(), index(), rindex(); can also use the in

operator.

2. Identiers
import string alphas = string.letters + '_' alnums = alphas + string.digits iden = raw_input('Identifier to check? ') if len(iden) > 0: if iden[0] not in alphas: print "Error: first char must be alphabetic" else: if len(iden) > 1: for eachChar in iden[1:]: if eachChar not in alnums: print "Error: others must be alnum" break else: import keyword if iden not in keyword.kwlist: print 'ok' else: print 'Error: keyword name' else: print 'Error: no identifier entered'

Chun_AppA.fm Page 1015 Wednesday, August 23, 2006 5:19 PM

Answers to Selected Exercises

1015

Chapter 7
1. Dictionary methods
dict.update()

3. Dictionary methods
a)
keys = dict.keys() keys.sort()

or
sorted(dict.keys())

4. Creating dictionaries
# assumes and list2 are the same length d = {} for i in range(len(list1)): d[list1[i]] = list2[i]

or
d = {} for i, x in enumerate(list1): d[x] = list2[i]

or
d = dict(map(None, list1, list2))

or
d = dict(zip(list1, list2))

7. Inverting dictionaries
list1 = oldDict.values() list2 = oldDict.keys()

Now apply the solutions to Problem 4. Note that these solutions are destructive, meaning that for one-to-many dictionaries, keys that share the same values will only have the latest installed value for the value that is now a key. Extra Credit: Come up with a non-destructive solution where keys that share the same values in the old dictionary are now stored inside a list as the value for the corresponding key in the new dictionary.

Chun_AppA.fm Page 1016 Wednesday, August 23, 2006 5:19 PM

1016

Appendix A

Chapter 8
3. range() built-in function
a)
range(10)

4. Prime numbers
import math def isprime(num): count = int(math.sqrt(num)) while count > 1: if num % count == 0: return False count -= 1 else: return True

Chapter 9
2. File access
f = i = num for open(raw_input('enter filename: ')) 0 = int(raw_input('enter number of lines: ')) eachLine in f: if i == num: break print eachLine, # suppress NEWLINE i += 1 f.close()

13. Command-line arguments
b)
import sys print "# of args", len(sys.argv) print "args:", sys.argv # argc # argv

Chapter 10
1. Raising exceptions
e)

2. Raising exceptions
d)

Chun_AppA.fm Page 1017 Wednesday, August 23, 2006 5:19 PM

Answers to Selected Exercises

1017

4. Keywords
try-except monitors the try clause for exceptions and execution jumps to the matching except clause. However, the finally clause of a tryfinally will be executed regardless of whether or not an exception occurred. How does the try-except-finally statement work?

5. Exceptions (we'll provide the solution, but you have to determine why):
a) SyntaxError b) IndexError c) NameError d) ZeroDivisionError e) ValueError f) TypeError

Chapter 11
2. Functions
def sumtimes(x, y): return (x+y, x*y)

6. Variable-length arguments
def printf(string, *args): print string % args

Chapter 12
2. Importing attributes
a) and
from mymodule import foo foo() import mymodule mymodule.foo()

b) If you use the import statement, the module name is brought into the local namespace, and foo() is only accessible from the module's namespace. If you use the from-import statement, "foo()" itself is brought into the local namespace. In this case, you do not need to use the module's namespace to access it.

Chun_AppA.fm Page 1018 Wednesday, August 23, 2006 5:19 PM

1018

Appendix A

Chapter 13
2. Functions versus methods
Methods are basically functions but tied to a specic class object type. They are dened as part of a class and are executed as part of an instance of that class.

15. Delegation
It makes no difference whether we use open() or capOpen() to read our le because in capOpen.py, we delegated all of the reading functionality to the Python system defaults, meaning that no special action is ever taken on reads. The same code would be executed, i.e., none of read(), readline(), or readlines() are overridden with any special functionality.

Chapter 14
1. Callable objects
Functions, methods, classes, callable class instances

3. input() vs. raw_input()
raw_input() returns user input as a string; input() returns the evaluation of the user input as a Python expression. In other words:
input()

≡ eval(raw_input())

Chapter 15
Regular expressions 1. Matching strings
bat, hat, bit, etc. [bh][aiu]t

2. First name last
[A-Za-z-]+ [A-Za-z-]+ (Any pair of words separated by a single space, e.g., rst and last names, hyphens allowed)

3. Last name rst
[A-Za-z-]+, [A-Za-z] (Any word and single letter separated by a comma and single space, e.g., last name, rst initial) [A-Za-z-]+, [A-Za-z-]+

Chun_AppA.fm Page 1019 Wednesday, August 23, 2006 5:19 PM

Answers to Selected Exercises

1019

(Any pair of words separated by a comma and single space, e.g., last, rst names, hyphens allowed)

8. Python longs
\d+[lL] (Decimal [base 10] integers only)

9. Python oats
[0-9]+(\.[0-9]*)? (Describes a simple oating point number, that is, any number of digits followed optionally by a single decimal point and zero or more numeric digits, as in "0.004," "2," "75.," etc.)

Chapter 16
3. Sockets
TCP

6. Daytime service
>>> import socket >>> socket.getservbyname('daytime', 'udp') 13

Chapter 17
20. Identiers
pass is a keyword, so it cannot be used as an identier. The common idiom in all such cases is to append an underscore ( _ ) to the name of the offending variable.

Chapter 18
2. Python threads
I/O-bound . . . why?

Chapter 19
1. Client/server architecture
Window(ing) clients are GUI events generated usually by users which must be processed by the window(ing) system that acts as the server; it is responsible for making timely updates to the display as to be apparent to the user.

Chun_AppA.fm Page 1020 Wednesday, August 23, 2006 5:19 PM

1020

Appendix A

Chapter 20
15. CGI errors
The Web server returns either no data or error text, which results in an HTTP 500 or Internal Server Error in your browser because that (returned data) is not valid HTTP or HTML data. The cgitb module captures the Python traceback and returns it as valid data through CGI, which gets displayed to the user . . . a great debugging tool.

Chapter 21
1. Extending Python
Performance improvement Protecting source code New or desired change of functionality And more!

Chapter 22
1. DB-API
The DB-API is a common interface specication for all Python database adapters. It is good in that it forces all adapter writers to code to the same specication so that end-user programmers can write consistent code that can be (more) easily ported to other databases with the minimum amount of effort.

Chapter 23
3. Web services and the csv module
Replace the for loop in stock.py with the following:
import csv for tick, price, chg, per in csv.reader(f): print tick.ljust(7), ('%.2f' % round(float(price), 2)).rjust(6), chg.rjust(6), per.rjust(6)


相关文章:
Python核心编程第二版-习题答案_图文.pdf
Python核心编程第二版-习题答案 - Chun_AppA.fm Page 1
PYTHON核心编程第二版第2章习题答案.pdf
PYTHON核心编程第二版第2章习题答案 - 2-1.变量,print 和字符串
PYTHON核心编程第二版第8章习题答案.pdf
PYTHON核心编程第二版第8章习题答案 - 8-1.条件语句。请看下边的代码:
python核心编程第二版第2章习题答案.doc
python核心编程第二版第2章习题答案_教育学_高等教育_教育专区。python核心编程第二版第2章习题答案 2-1.变量,print 和字符串格式化操作符。启动交互式解释器,给...
python核心编程第二版第4章习题答案.doc
python核心编程第二版第4章习题答案 - 4-1.Python 对象。与所有
PYTHON核心编程(第二版)第十章习题答案.pdf
PYTHON核心编程(第二版)第十章习题答案_电子/电路_工程科技_专业资料。1
Python核心编程(第二版)-习题答案_图文.pdf
Python核心编程(第二版)-习题答案_计算机软件及应用_IT/计算机_专业资料 暂无评价|0人阅读|0次下载 | 举报文档 Python核心编程(第二版)-习题答案_计算机软件及...
python核心编程第二版第9章习题答案.doc
python核心编程第二版第9章习题答案 - 91. 文件过滤. 显示一个文件
python核心编程第二版第9章习题答案.doc
python核心编程第二版第9章习题答案 - 91. 文件过滤. 显示一个文件
python核心编程第二版第8章习题答案.doc
python核心编程第二版第8章习题答案_教育学_高等教育_教育专区。python核心编程第二版第8章习题答案 8-1.条件语句。请看下边的代码: # statement A if x > ...
Python核心编程(第二版)第十章习题答案.doc
Python核心编程(第二版)第十章习题答案 - 10.1 引发异常。以下的哪个
python核心编程第二版课后题答案第六章.doc
python核心编程第二版课后题答案第六章_工学_高等教育_教育专区。python核心编程第二版课后题答案,转载,仅供参考 def idcheck(): '''6-2 修改 idcheck 使之...
PYTHON核心编程第二版课后题答案第八章.pdf
PYTHON核心编程第二版课后题答案第八章 - def loop(f, t, i
python核心编程第二版第7章习题答案.doc
python核心编程第二版第7章习题答案_教育学_高等教育_教育专区。python核心编程第二版第7章习题答案 7-1.字典方法。哪个字典方法可以用来把两个字典合并到一起。...
python核心编程第二版第3章习题答案.doc
python核心编程第二版第3章习题答案_理学_高等教育_教育专区。python核心编程第二版第3章习题答案 3-1.标识符。为什么 Python 中不需要变量名和变量类型声明? ...
Python核心编程第三版课后习题解答(第四章).doc
Python核心编程第版课后习题解答(第四章)_计算机软件及应用_IT/计算机_专业...4-6.多线程网络聊天室 参考第二章中的习题解答。 4-8.线程池,一个生产者...
python核心编程第二版课后题答案第五章.doc
python核心编程第二版课后题答案第五章_工学_高等教育_教育专区。python核心编程第二版课后题答案,转载,仅供参考 def ji(x1, x2): '''5-2 返回两个数的...
python核心编程第二版课后题答案第七章.doc
python核心编程第二版课后题答案第七章_理学_高等教育_教育专区。python核心编程第二版课后题答案,转载,仅供参考 def orderdict(mydict): '''7-3(a)创建一个...
PYTHON核心编程第二版课后题答案第六章.pdf
PYTHON核心编程第二版课后题答案第六章 - def idcheck(): &
python核心编程第七章7-5习题答案.txt
python核心编程第七章7-5习题答案 - db={} def manage_list...... python核心编程第七章7-5习题答案_理学_高等...Python核心编程第二版-习... 10页 免费 ...
更多相关文章: