Learning python 读书笔记 PART 3
PART THREE: Statements and Syntax
Chapter 8. Assignment, Expressions, and Print
program are composed of modules contains statements contain expressions create and process objects
1. Assignment Statements
a = 'a'
a, b = 'a', 'b' #tuple assignment
[a,b] = ['a','b'] #List assignment
a = b = 'c' #Mutiple-assignment
L = L + [3], L = L + [5,6] #Concatenate(create a new object)
L.append(3), L.extend([4,5]) #Faster, but in-place(add at the and of memory)
L += [9,10] #Mapped to L.extend([9,10]): the faster mothed
2. Expression Statements
3. Print Statements
print a,b, #don't add newline at the end of text
print >>myfile a,b #send data to myfile.write, not to sys.stdout.write
redirecting the Output Stream
import sys
sys.stdout = open('myfile', 'a')
print and stdout
class FileFaker:
def write(self, string) #do something with the string
import sys
sys.stdout = FileFaker()
Chapter 9. if Tests
1. if stataments
if: elif: else:
if 1:
print 'true'
else:
print 'false'
switch & case:
*if choice = 'a':
print 'aaa'
elif choice = 'b':
print 'bbb'
else:
print 'default'
choice = 'b'
*print {'a':'aaa','b':'bbb'}[choice]
*branch = {'a':'aaa','b':'bbb'}
print branch.get('a', 'bad choice')
2. truth tests
2<3, 3<2 #Less-than: return 1 or 0
short circuit evaluation
2 or 3, 3 or 2 #(2,3) Return left operand if true. Else return right operand.
[] or 3 #3
[] or {} #{}
2 and 3, 3 and 2 #(3,2) return left operand if false. Else return right operand.
Chapter 10. while and for Loops
1. while loops
while <test>:
<statement1>
if <test2>: break #Exit loop now, skip now
if <test2>: continue #goto top of loop now
else:
<statement2> #if we didn't hit break
breaks, continue, pass and the loop else
Emulating C while Loops
C assignments return the value assignment; Python assignments are just statements, not expressions
C: while ((x = next()) != NULL){process x...}
Python equivalent:
*while 1:
x = next()
if not x: break
...process...
x = 1
*while x:
x = next()
if x:
...process
2. for loops
for <target> in <object>:
<statements>
else:
<statements> #if we didn't hit break
3. loop variations
range
Counter Loops
range(3) #[0,1,2]
range(2,5) #[2,3,4]
range(0,10,2) #[0,2,4,6,8]
*for item in X: print item
*i = 0
while i < len(X)
print x[i],; i += 1
*for i in range(len(x)): print X[i]
Nonexhaustive Traversals
S = 'abcdefghijk'
for i in range(0, len(s), 2) print S[i], #manual for indexing
for i in S[::2]: print x
Changing Lists
for i in range(len(L)):
L[i] += 1
zip and map
zip can enable us to visit multiple sequences in parallel
L1 = [1,2,3], L2 = [4,5,6]
zip(L1,L2) #[(1,4),(2,5),[3,6]]
for (x,y) in zip(L1,L2):
print x, y,
when argument lengths differ, zip choose the shortest length
map(None, L1, L2)
map choose the longest length and filled empty items with "None"
Dictionary Construction with zip
>>> keys = ['a','b','c']
>>> values = [1,2,3]
>>> zip(keys,values)
[('a', 1), ('b', 2), ('c', 3)]
>>> D = {}
>>> for(k,v)in zip(keys,values):
D[k]= v
>>> D
{'a': 1, 'c': 3, 'b': 2}
>>> D2 = dict(zip(keys,values))
>>> D2
{'a': 1, 'c': 3, 'b': 2}
File Scanners
file = open('test.txt', 'r')
while 1:
line = file.readline()
if not line: break
print line
1. for line in open('test.txt').readlines(): print line
2. for line in open('test.txt').xreadlines(): print line
3. for line in open('test.txt'): print line
xreadlines loads lines on demand, "3" relies on iterators, is equivalent of xreadlines
Chapter 11. Documenting Python Code
1. the python document interlude
__doc__: In-file documentation attached to objects
docstrings
User-defined docstrings: strings at the top of file, method and class
built-in docstring:
import sys
print sys.__doc__
print int.__doc__, print open.__doc__
pydoc
help(sys)
2. common coding gotthas
Don't forget the colons
Start in column 1
Blank lines matter at the interactive prompt:
mean the end of compound statement
Indent consistently
Don't coding C in Python:
don't embed assignment statements in while loop tests
Use simple for loop instead of while or range:
for loop is simple and fast
Don't expect results from functions that change objects in-place:
append(), sort(), append(), extend()
myList = myList.append(X) #set myList to None
Always use parenthesis to call a function
Don't use extensions or paths in imports and reloads
0 comments:
Post a Comment