Debian Codegraph @

doc/source/main/basic_python_coding.rst

raw
1 Basic Python Coding
2 ===================
3
4 In this course you will learn basic programming in Python, but there is also
5 excellent Python Language reference material available on the internet freely.
6 You can download the book `Dive Into Python <http://www.diveintopython.org/>`_
7 or there are a host of `Beginners Guides <http://wiki.python.org/moin/BeginnersGuide>`_
8 to Python on the Python Website. Follow the links to either:
9
10 + `BeginnersGuide/NonProgrammers <http://wiki.python.org/moin/BeginnersGuide/NonProgrammers>`_
11 + `BeginnersGuide/Programmers <http://wiki.python.org/moin/BeginnersGuide/Programmers>`_
12
13 depending on your level of current programming knowledge. The code sections
14 below assume a knowledge of fundamental programming principles and mainly
15 focus on Syntax specific to programming in Python.
16
17 Note: >>> represents a Python command line prompt.
18
19
20 Loops in Python
21 ---------------
22
23 for Loop
24 ~~~~~~~~
25
26 The general format is:
27
28
29 .. code-block:: python
30
31 for variable in sequence:
32 #some commands
33 #other commands after for loop
34
35
36 Note that the formatting (indents and new lines) governs the end of the for
37 loop, whereas the start of the loop is the colon :.
38
39 Observe the loop below, which is similar to loops you will be using in the
40 course. The variable i moves through the string list becoming each string in
41 turn. The top section is the code in a .py file and the bottom section shows
42 the output
43
44 .. code-block:: python
45
46 #The following code demonstrates a list with strings
47 ingredientslist = ["Rice","Water","Jelly"]
48 for i in ingredientslist:
49 print i
50 print "No longer in the loop"
51
52 gives
53
54 .. code-block:: python
55
56 Rice
57 Water
58 Jelly
59 No longer in the loop
60
61
62 while Loop
63 ~~~~~~~~~~
64
65 These are similar to for loops except they continue to loop until the specified
66 condition is no longer true. A while loop is not told to work through any
67 specific sequence.
68
69
70 .. code-block:: python
71
72 i = 3
73 while i <= 15:
74 # some commands
75 i = i + 1 # a command that will eventually end the loop is naturally
76 required
77 # other commands after while loop
78
79
80 For this specific simple while loop, it would have been better to do as a for
81 loop but it demonstrates the syntax. while loops are useful if the number of
82 iterations before the loop needs to end, is unknown.
83
84 The if statement
85 ~~~~~~~~~~~~~~~~
86
87 This is performed in much the same way as the loops above. The key identifier is
88 the colon : to start the statements and the end of indentation to end it.
89
90
91 .. code-block:: python
92
93 if j in testlist:
94 # some commands
95 elif j == 5:
96 # some commands
97 else:
98 # some commands
99
100
101 Here it is shown that "elif" (else if) and "else" can also be used after an if
102 statement. "else" can in fact be used after both the loops in the same way.
103
104 Array types in python
105 --------------------------
106
107 Lists
108 ~~~~~
109
110 A list is simply a sequence of variables grouped together. The range function is
111 often used to create lists of integers, with the general format of
112 range(start,stop,step). The default for start is 0 and the default for step is
113 1.
114
115
116 >>> range(3,8)
117 [3,4,5,6,7]
118
119
120 This is a list/sequence. As well as integers, lists can also have strings in
121 them or a mix of integers, floats and strings. They can be created by a loop
122 (as shown in the next section) or by explicit creation (below). Note that the
123 print statement will display a string/variable/list/... to the user
124
125
126 >>> a = [5,8,"pt"]
127 >>> print a
128 [5,8,'pt']
129 >>> print a[0]
130 5
131
132 Tuples
133 ~~~~~~
134
135 Tuples are basically the same as lists, but with the important difference that
136 they cannot be modified once they have been created. They are assigned by:
137
138
139 >>> x = (4,1,8,"string",[1,0],("j",4,"o"),14)
140
141
142 Tuples can have any type of number, strings, lists, other tuples, functions and
143 objects, inside them. Also note that the first element in the tuple is numbered
144 as element "zero". Accessing this data is done by:
145
146
147 >>> x[0]
148 4
149 >>> x[3]
150 "string"
151
152
153 Dictionaries
154 ~~~~~~~~~~~~
155
156 A Dictionary is a list of reference keys each with associated data, whereby the
157 order does not affect the operation of the dictionary at all. With dictionaries,
158 the keys are not consecutive integers (unlike lists), and instead could be
159 integers, floats or strings. This will become clear:
160
161
162 >>> x = {} # creates a new empty dictionary - note the curly brackets denoting the creation of a dictionary
163 >>> x[4] = "programming" # the string "programming" is added to the dictionary x, with "4" as it's reference
164 >>> x["games"] = 12
165 >>> print x["games"]
166 12
167
168
169 In a dictionary, the reference keys and the stored values can be any type of
170 input. New dictionary elements are added as they are created (with a list, you
171 cannot access or write to a place in the list that exceeds the initially defined
172 list dimensions).
173
174
175 .. code-block:: python
176
177 costs = {"CHICKEN": 1.3, "BEEF": 0.8, "MUTTON": 12}
178 print "Cost of Meats"
179 for i in costs:
180 print i
181 print costs[i]
182 costs["LAMB"] = 5
183 print "Updated Costs of Meats"
184 for i in costs:
185 print i
186 print costs[i]
187
188 gives
189
190 .. code-block:: python
191
192 Cost of Meats
193 CHICKEN
194 1.3
195 MUTTON
196 12
197 BEEF
198 0.8
199 Updated Costs of Meats
200 LAMB
201 5
202 CHICKEN
203 1.3
204 MUTTON
205 12
206 BEEF
207 0.8
208
209
210 In the above example, the dictionary is created using curly brackets and colons
211 to represent the assignment of data to the dictionary keys. The variable i is
212 assigned to each of the keys in turn (in the same way it would be for a list
213 with
214
215 >>> for i in range(1,10)
216
217 ). Then the dictionary is called with this key, and
218 it returns the data stored under that key name. These types of for loops using
219 dictionaries will be highly relevant in using PuLP to model LPs in this course.
220
221 List/Tuple/Dictionary Syntax Note
222 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
223
224 Note that the creation of a:
225
226 - list is done with square brackets [];
227 - tuple is done with round brackets and a comma (,);
228 - dictionary is done with parentheses{}.
229
230 After creation however, when accessing elements in the list/tuple/dictionary,
231 the operation is always performed with square brackets (i.e a[3]?). If a was a
232 list or tuple, this would return the fourth element. If a was a dictionary it
233 would return the data stored with a reference key of 3.
234
235 List Comprehensions
236 ~~~~~~~~~~~~~~~~~~~
237
238 Python supports List Comprehensions which are a fast and concise way to create
239 lists without using multiple lines. They are easily understandable when simple,
240 and you will be using them in your code for this course.
241
242
243 >>> a = [i for i in range(5)]
244 >>> a
245 [0, 1, 2, 3, 4]
246
247
248 This statement above will create the list [0,1,2,3,4] and assign it to the
249 variable "a".
250
251
252 >>> odds = [i for i in range(25) if i%2==1]
253 >>> odds
254 [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
255
256 This statement above uses the if statement and the modulus operator(%) so that
257 only odd numbers are included in the list: [1,3,5,...,19,21,23]. (Note: The
258 modulus operator calculates the remainder from an integer division.)
259
260
261 >>> fifths = [i for i in range(25) if i%5==0]
262 >>> fifths
263 [0, 5, 10, 15, 20]
264
265 This will create a list with every fifth value in it [0,5,10,15,20]. Existing
266 lists can also be used in the creation of new lists below:
267
268 >>> a = [i for i in range(25) if (i in odds and i not in fifths)]
269
270
271 Note that this could also have been done in one step from scratch:
272
273 >>> a = [i for i in range(25) if (i%2==1 and i%5==0)]
274
275 For a challenge you can try creating
276
277 a. a list of prime numbers up to 100, and
278 #. a list of all "perfect" numbers.
279
280
281 `More List Comprehensions Examples <http://www.secnetix.de/olli/Python/list_comprehensions.hawk>`_
282
283 `Wikipedia: Perfect Numbers <http://en.wikipedia.org/wiki/Perfect_numbers>`_.
284
285 Other important language features
286 ---------------------------------
287
288 Commenting in Python
289 ~~~~~~~~~~~~~~~~~~~~
290 Commenting at the top of a file is done using """ to start and to end the
291 comment section. Commenting done throughout the code is done using the hash
292 # symbol at the start of the line.
293
294 Import Statement
295 ~~~~~~~~~~~~~~~~
296
297 At the top of all your Python coding that you intend to use PuLP to model, you
298 will need the import statement. This statement makes the contents of another
299 module (file of program code) available in the module you are currently writing
300 i.e. functions and values defined in pulp.py that you will be required to call,
301 become usable. In this course you will use:
302
303 >>> from pulp import *
304
305 The asterisk represents that you are importing all names from the module of
306 pulp. Calling a function defined in pulp.py now can be done as if they were
307 defined in your own module.
308
309 Functions
310 ~~~~~~~~~
311
312 Functions in Python are defined by: (def is short for define)
313
314 .. code-block:: python
315
316 def name(inputparameter1, inputparameter2, . . .):
317 #function body
318
319 For a real example, note that if inputs are assigned a value in the function
320 definition, that is the default value, and will be used only if no other value
321 is passed in. The order of the input parameters (in the definition) does not
322 matter at all, as long as when the function is called, the positional parameters
323 are entered in the corresponding order. If keywords are used the order of the
324 parameters does not matter at all:
325
326 .. code-block:: python
327
328 def string_appender(head='begin', tail='end', end_message='EOL'):
329 result = head + tail + end_message
330 return result
331
332 >>> string_appender('newbegin', end_message = 'StringOver')
333 newbeginendStringOver
334
335 In the above example, the output from the function call is printed. The default
336 value for head is 'begin', but instead the input of 'newbegin' was used. The
337 default value for tail of 'end' was used. And the input value of endmessage was
338 used. Note that end_message must be specified as a key word argument as no
339 value is given for tail
340
341 Classes
342 ~~~~~~~
343
344 To demonstrate how classes work in Python, look at the following class structure.
345
346 The class name is Pattern, and it contains several class variables which are
347 relevant to any instance of the Pattern class (i.e a Pattern). The functions are
348
349 __init__
350 function which creates an instance of the Pattern
351 class and assigns the attributes of name and lengthsdict using self.
352
353 __str__
354 function defines what to return if the class instance is printed.
355
356 trim
357 function acts like any normal function, except as with all class functions,
358 self must be in the input brackets.
359
360 .. code-block:: python
361
362 class Pattern:
363 """
364 Information on a specific pattern in the SpongeRoll Problem
365 """
366 cost = 1
367 trimValue = 0.04
368 totalRollLength = 20
369 lenOpts = [5, 7, 9]
370
371 def __init__(self,name,lengths = None):
372 self.name = name
373 self.lengthsdict = dict(zip(self.lenOpts,lengths))
374
375 def __str__(self):
376 return self.name
377
378 def trim(self):
379 return Pattern.totalRollLength - sum([int(i)*self.lengthsdict[i] for i in self.lengthsdict])
380
381 This class could be used as follows:
382
383 >>> Pattern.cost # The class attributes can be accessed without making an instance of the class
384 1
385 >>> a = Pattern("PatternA",[1,0,1])
386 >>> a.cost # a is now an instance of the Pattern class and is associated with Pattern class variables
387 1
388 >>> print a # This calls the Pattern.__str__() function
389 "PatternA"
390 >>> a.trim() # This calls the Pattern.trim() function. Note that no input is required.
391
392 The self in the function definition is an implied input