1 |
#!/usr/local/bin/python |
2 |
#---------------------------------------------------------------------------------------------------- |
3 |
#$Header$ |
4 |
#---------------------------------------------------------------------------------------------------- |
5 |
#David T. Ashley, 11/2018 |
6 |
#---------------------------------------------------------------------------------------------------- |
7 |
#This file contains notes and experiments as I worked through Mark Lutz's book, "Learning |
8 |
#Python: Powerful Object-Oriented Programming 5th Edition, Kindle Edition", Chapter 4. |
9 |
#---------------------------------------------------------------------------------------------------- |
10 |
import sys |
11 |
import math #Many math functions available in Python libraries. |
12 |
|
13 |
#Math functions built in. |
14 |
x = math.pi |
15 |
print(x) |
16 |
y = math.sqrt(x) |
17 |
print(y) |
18 |
|
19 |
#String assignment. |
20 |
s = 'Now is the time for all good men to come to the aid of their country.' |
21 |
|
22 |
#Reference to single character. |
23 |
print(s[3]) |
24 |
|
25 |
#Reference to character range, called slices. Second |
26 |
#limit is < limit, i.e. open interval on the right. |
27 |
print(s[3:7]) |
28 |
|
29 |
#Can use one greater on the right to get full string. |
30 |
print(s[0:len(s)]) |
31 |
|
32 |
#Can use negative indices to go backwards in a string. |
33 |
print(s[3:-3]) |
34 |
|
35 |
#String concatenation. |
36 |
t = s+s |
37 |
print(t) |
38 |
|
39 |
#String repetition. |
40 |
u = s*10 |
41 |
print(u) |
42 |
|
43 |
#Strings are immutable (can't be changed in place). Illegal assignment below: |
44 |
#s[0] = 'q' |
45 |
#Must instead construct new string and assign. |
46 |
|
47 |
#list: expands to list. |
48 |
l=list(s) |
49 |
print(l) |
50 |
|
51 |
#Can omit left or right limits, in which case defaults to first and last elements. |
52 |
print(s[:3]) |
53 |
print(s[3:]) |
54 |
print(s[:]) |
55 |
|
56 |
#Byte arrays. Literals are b'chars'. Created with bytearray(). |
57 |
ba=bytearray(b'spam') |
58 |
ba.extend(b'eggs') |
59 |
print(ba) |
60 |
bad=ba.decode() |
61 |
print(bad) |
62 |
|
63 |
#Determining which system one is running on. |
64 |
print(sys.platform) |
65 |
|
66 |
#Arbitrary-precision arithmetic: integers grow automatically. |
67 |
print(2**100) |
68 |
|
69 |
#String repetition. |
70 |
x = 'Spam! ' |
71 |
print(x*8) |
72 |
|
73 |
#Pausing to accept the <ENTER> key--useful when using an icon to launch |
74 |
#a script. |
75 |
#input() |
76 |
|
77 |
#String concatenation, comment. |
78 |
print('The bright side of' + ' Life ...') #Comment. |
79 |
|
80 |
#Built in methods. Conversion of strings to lists. |
81 |
s='Spam' |
82 |
print(s.find('pa')) |
83 |
print(s.replace('pa', 'XYZ')) |
84 |
line='aaa,bbb,ccccc,dd' |
85 |
print(line.split(',')) |
86 |
print(s.upper()) |
87 |
print(s.isalpha()) |
88 |
print(s.isdigit()) |
89 |
|
90 |
#Standard string operations that may be useful. |
91 |
line='aaa,bbb,ccccc,dd' |
92 |
print(line.rstrip()) |
93 |
|
94 |
#Combine two operations. Note that rstrip() runs first, because Python does |
95 |
#this from left to right. This is counterintuitive, at least to me. |
96 |
print(line.rstrip().split(',')) |
97 |
|
98 |
#Formatting. This seems to behave essentially like sprintf() in C. |
99 |
print('%s, eggs, and %s' % ('spam', 'SPAM!')) |
100 |
print('{0}, eggs, and {1}'.format('spam', 'SPAM!')) |
101 |
print('{1}, eggs, and {0}'.format('spam', 'SPAM!')) |
102 |
print('{1}, eggs, and {1}'.format('spam', 'SPAM!')) |
103 |
print('{:,.2f}'.format(296999.2567)) |
104 |
print('%.2f | %+05d' % (3.14159, -42)) |
105 |
|
106 |
#Find out what methods are available for strings. The names with |
107 |
#double underscores are for operator overloading, discussed later. |
108 |
#In general, the names with leading or trailing double underscores |
109 |
#have to do with implementation of Python internals. |
110 |
q='Now is the time' |
111 |
print(dir(q)) |
112 |
|
113 |
#Python has built-in help for methods. |
114 |
print(help(q.replace)) |
115 |
|
116 |
#Can also get help for a data type (string). |
117 |
#print(help(str)) |
118 |
|
119 |
#Can encode string characters as hex constants. |
120 |
s='A\nB\tC' |
121 |
print(len(s)) |
122 |
|
123 |
#ord() returns the decimal value of a character. |
124 |
print(ord('\n')) |
125 |
|
126 |
#Double quotes allowed in string constants. |
127 |
#Triple quotes(single or double) allowed. This allows multi-line |
128 |
#text to be included. Line breaks in a constant occur as well. |
129 |
triple_quoted_string = '''Now is the time |
130 |
for all good men to come to the aid of their |
131 |
country, and the line break should be next |
132 |
line break shold be before''' |
133 |
print(triple_quoted_string) |
134 |
triple_quoted_string2 = """Now is the time |
135 |
for all good men to come to the aid of their |
136 |
country, and the line break should be next |
137 |
line break shold be before""" |
138 |
print(triple_quoted_string2) |
139 |
|
140 |
#Can add triple quotes on both sides to disable a block of code. |
141 |
|
142 |
#Raw string literals prefixed with "r": turns off backslash escape mechanism. |
143 |
raw_literal=r'C:\text\new' |
144 |
print(raw_literal) |
145 |
|
146 |
#Unicode is supported, and literals prefixed with "u". Normal string functions |
147 |
#handle Unicode as well as ASCII. Need to review that later. |
148 |
unicode_string=u'sp\u00c4m' |
149 |
print(unicode_string) |
150 |
|
151 |
#Book made the statement that ASCII is a special case of Unicode--need to review that statement |
152 |
#and Unicode encoding and be sure I understand it. |
153 |
|
154 |
#There is a distinct "bytes" string type for binary values (like raw file contents, |
155 |
#I'd guess). Prefix is "b". |
156 |
binary_string=b'a\x01c' |
157 |
print(binary_string) |
158 |
print(len(binary_string)) |
159 |
|
160 |
#"re" is the module for pattern matching. Can do regular expression searching |
161 |
#and so on. |
162 |
|
163 |
#Lists |
164 |
#----- |
165 |
#Same sequence operations for strings apply. |
166 |
# len() |
167 |
# indexing and slicing |
168 |
# repetition |
169 |
#Can freely mix types. |
170 |
#Can add and remove elements (append, pop, other operations). |
171 |
#Can sort and reverse. |
172 |
#Can index off the end or assign off the end. (To assign off the end, must |
173 |
#use append method or similar. Can't just assign.) |
174 |
#Python allows nesting. (A list of lists, or a list of dictionaries, each of which |
175 |
#contain other lists.) |
176 |
#A list of lists can be double-indexed, i.e. list[1][2]. |
177 |
# |
178 |
#One way to think about matrix[m][n] is that matrix[m] grabs the entire row "m" |
179 |
#(a list itself), then [n] indexes into that list. |
180 |
matrix=[[1,2,3],[4,5,6],[7,8,9]] |
181 |
print(matrix) |
182 |
print('Element[0][0] is: ' + str(matrix[0][0])) |
183 |
print('Element[1][2] is: ' + str(matrix[1][2])) |
184 |
|
185 |
#Comprehensions |
186 |
#-------------- |
187 |
#List comprehension / list comprehension expression: |
188 |
# o Derive from set notation. |
189 |
# o Build a new list by running an expression on each item in a sequence, one at a time, from |
190 |
# left to right. |
191 |
# o Consist of an expression and a looping construct that share a variable name. |
192 |
#In the code below, each element of matrix is obtained (a row), then for each row column[1] |
193 |
#is extracted, and this is placed in a list. |
194 |
col2 = [row[1] for row in matrix] |
195 |
print(col2) |
196 |
diagonal = [matrix[i][i] for i in [0, 1, 2]] |
197 |
print(diagonal) |
198 |
|
199 |
#Dictionaries |
200 |
#------------ |
201 |
#Mappings from key to value. |
202 |
#Mutable: can be changed in place and grow and shrink on demand. |
203 |
#Assignments with new keys create the keys (unlike lists, where this is forbidden). |
204 |
d={'food': 'Spam', 'quantity': 4, 'color': 'pink'} |
205 |
print(d) |
206 |
#zip function can be used to combine parallel arrays into key:value dictionary. |
207 |
#Dictionary entries can be accessed as dict_name[key]. |
208 |
#The nested types in Python seem to be nearly as flexible as a tree in C (formed with malloc() and |
209 |
#friends. Dictionaries and lists have variable numbers of elements and can be nested arbitrarily |
210 |
#unevenly ... effectively a tree. |
211 |
#.keys() method: gets the keys of a dictionary. |
212 |
|
213 |
#For loops |
214 |
#--------- |
215 |
#for loop is an iterator. Will work on any iterable object. |
216 |
|
217 |
#Tuples |
218 |
#------ |
219 |
# o Immutable sequences. |
220 |
# o Coded in parenthesis. |
221 |
# o Can be arbitrarily nested. |
222 |
t=(1, 2, 3, 4) |
223 |
print(t) |
224 |
print(len(t)) |
225 |
print(t.index(4)) |
226 |
print(t.count(4)) |
227 |
#Tuples cannot be changed once created (immutable). |
228 |
|
229 |
#Files |
230 |
#----- |
231 |
#Created using open() and similar functions. |
232 |
#Functions: |
233 |
# f=open() |
234 |
# f.read() |
235 |
# f.write() |
236 |
# f.close() |
237 |
#File's contents are always a string. |
238 |
# for line in open('fname'): print(line) |
239 |
|
240 |
#Binary Files |
241 |
#------------ |
242 |
#Python "struct" module: can both create and unpack packed binary data. |
243 |
#Can open files with "b" option and so use binary strings. |
244 |
|
245 |
#Unicode in Files |
246 |
#---------------- |
247 |
#Can pass in an encoding name. Will read and write unicode as text. |
248 |
|
249 |
#Other Objects |
250 |
#------------- |
251 |
#Python can deal with pipes, FIFO's, sockets, etc. as well. |
252 |
|
253 |
#Sets |
254 |
#---- |
255 |
#Now supported in Python. |
256 |
#Include intersection, union, etc. |
257 |
|
258 |
#Other Numerical Types |
259 |
#--------------------- |
260 |
#Decimal numbers. |
261 |
#Fractions (i.e. rational numbers). |
262 |
|
263 |
#Booleans |
264 |
#-------- |
265 |
#Can only be False or True. |
266 |
|
267 |
#None |
268 |
#---- |
269 |
#Placeholder, commonly used to initialize names and objects. |
270 |
|
271 |
#type() |
272 |
#------ |
273 |
#Gives the type of another object. |
274 |
|
275 |
#User-Defined Classes |
276 |
#-------------------- |
277 |
#Supported. |
278 |
#---------------------------------------------------------------------------------------------------- |
279 |
|