· 9 years ago · Mar 06, 2017, 10:50 AM
1# PEP 8
2
3'''
4 - Long expressions' continuation should begin with 4 spaces of indent
5 - Functions and classes separated by 2 spaces
6 - One space before and after assignment
7'''
8## Naming stuff:
9
10''' functions, variables, and attributes: '''
11lower_undersocre
12
13''' protected: '''
14_leading_underscore
15
16''' private: '''
17__double_leading_underscore
18
19''' classes and exceptions: '''
20CapitalizedWord
21
22''' module-level constants: '''
23ALL_CAPS
24
25
26## Misc
27
28
29# TYPES, OPERATORS, AND VARIABLES
30
31 # You can use either ' ' or " " for strings, just stick with one
32'string'
33"string"
34
35 # Concatenate strings:
36'Hello ' ' world' # >>> 'Hello world'
37
38'Alice' * 5 # >>> AliceAliceAliceAliceAlice
39
40 # Get length of a string:
41len(string)
42
43 # Variables are created as you give them value.
44
45 # input function always returns a string so you have to convert it later
46name = input("What's your name? ")
47
48 # Print a string:
49print("Hello there " + name)
50
51 # Or use placeholders
52print("Hello there {0} from {1}".format(name, "New York")
53
54 # Change the separator and strip the newline character
55print("cat", "dog", "mouse", sep="_", end='') # >>> cat_dog_mouse
56
57 # Formatted strings: {placeholder: format_specifier}
58 # The general format of the specifier:
59 # [[fill[allign]][sign][0][width][.precision][type]
60'{0:#^10}'.format('Anna') # => ###Anna###
61 # Allignment > - right, < - left, ^ - center
62
63 # Logical:
64and or not
65
66 # Relational and arythmetic operators are like in C, with the exception of
672 ** 3 # >>> 8
68
69 # Comparision operators can be chained
70>>> 1 < 5 < 7 # => True
71
72 # * and + operators create shallow copies:
73a = [3,4,5]
74b = 4*a # => b = [[3,4,5], [3,4,5]]
75a[0] = -7 # => b = [[-7, 4, 5], [-7, 4, 5]]
76
77 # Swap two values in-place
78x, y = y, x
79
80# CONTAINERS
81## Lists:
82l = []
83l.append(2)
84
85 # Length:
86len(list)
87
88l = 'abcdefg'
89 # Get last item of the list:
90l[-1]
91
92 # Get first 5 items of the list:
93l[:5] # => abcde
94
95 # Get last 5:
96l[-5:]
97
98 # Copy a to to b
99b = a[:]
100
101 # Point bo to the same list
102b = a
103
104 # is checks if two variables point to the same object, == checks if those
105 # objects have the same value.
106a = [1, 2, 3, 4]
107b = [1, 2, 4, 5]
108a == b # >>> True
109a is b # >>> False
110
111 # Check if value is in the list
112animals = ["cat", "dog", "mouse"]
113>>> 'cat' in animals
114True
115
116>>> 'elephant' in animals
117False
118
119 # Also:
120vowels = ['aeiouyAEIOUY']
121>>> 'A' in vowels
122True
123
124 # Tuples are immutable:
125animals = ("cat", "dog", "mouse")
126>>> animals[i] = "elephant" # => ERROR
127
128 # Convert tuple, or string to a list:
129>>> list('hello')
130['h', 'e', 'l', 'l', 'o']
131
132 # All sequences can be unpacked into a sequence of variables
133l = [1, 2, 3]
134a,b,c = l # => a = 1, b = 2, c = 3
135
136letters = 'abc'
137x,y,z = letters
138
139 # Check if list is empty:
140if not l:
141 # Do something
142
143
144## Dictionaries
145
146 # Dictionaries map the key to the values. They are not ordered however,
147 # so you can't slice them:
148colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}
149
150>>> colors["red"] # => #FF0000
151
152
153 # These methods returns iterables
154colors.values() # => #FF0000, #00FF00, #0000FF
155colors.keys() # => red, blue, green
156colors.items() # => ('red', '##FF0000') ...
157
158 # You can iterate over them like:
159for v in colors.values():
160 print(v)
161
162 # Or use them to check if sth is in the dictionary:
163>>> "green" in colors.keys()
164True
165
166 # Use list comprehensions to derive one list from another:
167a = [1, 2, 3, 4, 5]
168squares = [x**2 for x in a] # => [1, 4, 9, 16, 25]
169
170 # Filter results you don't want:
171even_squares = [x**2 for x in a if x % 2 == 0] # => [4, 16]
172
173 # Nested:
174a = [-1, 1, 2, 3]
175b = 'abc'
176c = [(x, y) for x in a for y in b if x > 0]
177
178 # It's a little more clear with indentation:
179c = [(x, y) for x in a
180 for y in b
181 if x > 0]
182
183 # Generator expressions is similiar to list comprehension, but it doesn't
184 # produce a list immediately, instead it returns a generator object that
185 # produces the values on demand during iteration:
186a = [1,2,3,4]
187b = (x*10 for x in a)
188b.__next__() # => 10
189b.__next__() # => 20
190
191 # Generator expressions are better performence-wise, for example when
192 # parsing some text files you don't have to read the entire file at once.
193 # Use generator expressions when you only need to iterate over something
194 # once, and when the sequence is very large on infinite, otherwise use
195 # list comprehensions
196
197
198
199## Sets
200
201 # Set is an unordered collection with no duplicates
202some_set = {1, 2, 3, 4, 1, 2} # => {1, 2, 3, 4}
203
204 # They use {} to initialize them, but empty set is created like this:
205s = set()
206
207 # Add one element to the set:
208s.add('cat')
209
210 # Add multiple elements:
211s.update(['dog', 'mouse'])
212
213#CONTROL FLOW
214
215 # If is the same as everywhere
216if a > 10:
217 print("Will print this if a > 10 is true")
218elif a > 2:
219 print("Will print this if a > 2 is true and the if clause isn't")
220else:
221 print("Print this in all the other cases")
222
223 # while loop looks like this, and you can use break and continue in loops
224while True:
225 koniec = input()
226 if koniec == "koniec":
227 break
228
229 # for loop iterate over loops:
230for animal in ["Dog", "Elephant", "Cat", "Mouse"]:
231 print(animal)
232
233 # We can use range() function to generate a list of the numbers
234for i in range(0, 10, 2):
235 print(i)
236 # >>> 0, 2, 4, 6, 8
237
238 # If you want to loop over something like a list of strings, but also
239 # need to get the index, use enumerate function
240colors = ['blue', 'red', 'green', 'yellow']
241for i, color in enumerate(colors):
242 print('{}: {}'.format(i+1, color)
243
244 # enumerate creates a list of tuples with a string and a number, this
245 # instruction unpacks the tuples into i & color
246
247 # You can apply a second parameter to specify where it'll start counting:
248for i, color in enumerate(colors, 1)
249
250 # Use zip to iteratore over multiple iterarators (?) at the same time:
251countries = ['United Kingdom', 'Poland', 'Czech Republic']
252capitals = ['London', 'Warsaw', 'Prague']
253
254for country, capital in zip(countries, capitals):
255 print(country, capital)
256
257 # Zip creates a list of tuples [(countries[0], capitals[0]), ...]
258
259# FUNCTIONS
260
261 # Declare simple functions with def
262def print_hello():
263 print("HELLO")
264
265 # Inwoke them like this:
266print_hello()
267
268 # Functions can obviously take arguments and return values
269def add(a, b):
270 return int(a) + int(b)
271
272 # To access global variable inside a function use global keyword:
273a = 10
274
275def change_a():
276 global a
277 a = 5
278
279 # If you don't do this, local variable with the same name is created
280def doesnt_change_a():
281 a = 5
282
283doesnt_change_a()
284print(a) # => 10
285
286 # Generator is a function that produces a sequence as a result
287def count(n):
288 print('Counting to {}'.format(n))
289 for i in range(1, n+1):
290 yield i
291 return
292
293 # yield is like return, except that it doesn't quit the function
294 # The following doesn't execute, instead it returns a generator object
295c = count(10)
296
297 '''
298 If the last argument in a function definition begins with **, all
299 additional keyword arguments are placed in a dictionary and passed to
300 function (useful for configuration options etc.)
301 - args i a tuple of positional arguments
302 - kwargs is a dictionary of keyword args '''
303def spam(*args, **kwargs):
304 pass
305
306
307# CLASSES AND OOP
308
309class Dog:
310 ''' Class definition and methods should start with docstrings
311 describing what they do '''
312 # Class variable shared by all instances
313 counter = 0
314
315 def __init__(self, name):
316 # Instance variable
317 self.name = name
318 Dog.counter += 1
319
320 # Local variable, can't be accessed from other methods
321 var = 3
322
323 # A static method is an ordinary function that just happen to live in
324 # the namespace of the class
325class Foo():
326 @staticmethod
327 def add(x,y):
328 return x+y
329x = Foo.add(3,4) # => x = 7
330
331 # properties are used like attributes, except they're read-only
332class Circle:
333 def __init__(self, radius):
334 self.radius = radius
335
336 @property
337 def area(self):
338 return 3.14*self.radius**2
339
340a = Circle(4)
341a.area # => 50.24
342
343''' Instance methods should use self as the name of the first parameter '''
344def __init__(self):
345 pass
346
347''' Class methods should use cls: (do we use cls like this?) '''
348def __init__(cls):
349 pass
350
351# EXCEPTIONS
352
353 # Catch all exceptions except for those related to program quit
354try:
355 # do something
356except Exception as e:
357 pass
358
359# DECORATORS
360
361 # Decorator is a function(for simplicity's sake) that takes a function
362 # object as an argument and returns a function object as a return value
363
364 # Decorators are used to add features to original function, in other words
365 # they are used to create a function that does roughly the same stuff as
366 # the original function but with some additional stuff
367
368 # EXAMPLES:
369
370 # Our decorator:
371def p_decorator(original_func):
372 def new_func(name):
373 return '<p>{0}</p>'.format(original_func(name))
374 return new_func
375
376 # The function we'll decorate
377def get_text(name):
378 return 'So your name is {0}'.format(name)
379
380 # We could use this like this:
381my_get_text = p_decorator(get_text)
382print(my_get_text("Albert")) # => <p>So your name is Albert</p>
383
384 # Or even like this:
385get_text = p_decorator(get_text)
386
387 # But Python provides some syntatic sugar, so we apply the decoration before
388 # the definition of the function we want to decorate:
389@p_decorator
390def get_text(name):
391 return 'So your name is {0}'.format(name)
392
393 # And now we just use
394print(get_text("Andżej"))
395 # and there's no way to use the original function without the decoration
396
397
398 # Decorators can take arguments:
399def add_tag(tag_name):
400 def tag_decorate(func):
401 def wrapper(name):
402 return '<{0}>{1}</{0}>'.format(tag_name, func(name))
403 return wrapper
404 return tag_decorate
405
406 # And decorations can be stacked:
407
408@add_tag('div')
409@add_tag('p')
410def get_text(name):
411 return 'So your name is {0}'.format(name)
412
413print(get_text('Antoni')) # => <div><p>So your name is antoni</p></div>
414
415 # BEST EXAMPLE:
416def verbose(original_function):
417 def new_function(*args, **kwargs):
418 print("Entering", original_function.__name__)
419 original_functrion(*args, **kwargs)
420 print("Exiting", original_function.__name__)
421 return new_function
422
423# WORKING WITH FILES
424
425 # The builtin function open() opens a file and returns a file object
426 # open(filename [,mode [, bufsize]])
427f = open('foo', 'r')
428
429 '''
430 File modes:
431 - r - read, text mode
432 - w - write, text mode
433 - a - append, text mode
434 - r+ - read and write
435 - w+ - read and write, but file is first truncated
436 - rb - read, binary mode
437 - wb - write, binary mode
438 - ab - append, binary mode
439 '''
440
441 # Read some data and return it as a string
442f.read(size)
443
444 # Read a line
445f.readline()
446
447 # To read lines from a file you can also loop over the file object:
448for line in f:
449 print(line, end='')
450
451 # Writes the conents of a string to the file and returns the number of
452 # characters written.
453f.write('This is a test\n') # => 15
454
455 # Redirect the output of print funcion to a file:
456print('The values are', x, y, z, file = f)
457
458 # Good practice: use with keyword when dealing with file object. It makes
459 # sure that the file is properly closed.
460with open('file', 'r') as f:
461 read_data = f.read()
462
463# MODULES
464
465 # Best style of importing:
466import random # random.randint()
467import random as rn # rn.randint()
468
469 # After that you can use stuff from random like this:
470random.randint(1,10)
471
472 # You can also just import one function like:
473from random import randint
474
475 # And use it like:
476randint(1, 10)
477
478 # Imports all the definitions in a module except for those starting with _
479 # (Avoid this)
480from random import *
481
482 # Check if file is being executed directly or imported as a module:
483if __name__ == '__main__':
484 # yep
485else:
486 # it must've been a module
487
488 # Get the file path of imported module
489print(random)
490
491## SYS MODULE
492
493import sys
494
495 # Get the number of arguments
496len(sys.argv)
497
498 # The first arg is always the name of the file:
499sys.argv[0]
500
501 # ~ need to get back to this
502 # For more advanced command-line handling use optparse
503import optparse
504
505## OS MODULE
506
507 # Walking down the path and adding files from subdirs to one list:
508import os
509
510def get_filepaths(directory):
511 file_paths = []
512 for (root, directories, files) in os.walk(directory):
513 for filename in files:
514 filepath = os.path.join(root, filename)
515 file_paths.append(filepath)
516 return file_paths
517## REGULAR EXPRESSIONS
518
519 # They're in re module
520import re
521
522 # Match the sequence:
523s = "Hey, my email is ahmm@gmail.com, and what's yours?"
524re.search('\S@\S', s) # => ahmm@gmail.com
525
526 # Extract a match with ():
527match = re.search('(\w+)@(\w+.\w+)')
528
529match.group(0) # => ahmm@gmail.com
530match.group(1) # => ahmm
531match.group(2) # => gmail.com
532
533 # Gives a lists of all occurences of regex:
534s = "This thing costs $100.00, the other thing costs $50.00, and that one
535 is $36.50"
536re.findall('\$[0-9.]+', s) # => ['$100.00', '$50.00', '$36.50']
537
538 # Compile the pattern beforehand:
539pattern = re.compile(r'\w+@\w+.\w+')
540
541 # + and * are greedy by default:
542s = 'The-one-whose-name-cannot-be-spoken'
543re.findall('.+-', s) # => ['The-one-whose-name-cannot-be-']
544
545 # Non-greedy:
546re.findall('.+?-', s) # => ['The-', 'one-', 'whose-', 'name-', cannot-', 'be-']
547
548 # SPECIAL CHARACTERS:
549 . # match any character, except for newline
550 ^ # start of string
551 $ # end of string
552 * # match the preceding RE 0 or more times
553 + # match the preceding RE 1 or more times
554 ? # match the preceding RE 0 or 1 times
555 {m} # match exactly m copies
556 {m, n} # m to n
557 [] # set, examples:
558 [AEIOU], [A-Za-z], [0-9.]
559 [^5] # match anything but 5
560 A | B # match either A or B
561 () # extract everything between parantheses
562
563 # CHARACTER CLASSES:
564 \d # any digit [0-9]
565 \D # non digit [^0-9]
566 \s # any whitespace
567 \S # any non whitespace
568 \w # alhpanumeric [a-zA-Z0-9_]
569 \W # non-alphanumeric