Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # PEP 8
- '''
- - Long expressions' continuation should begin with 4 spaces of indent
- - Functions and classes separated by 2 spaces
- - One space before and after assignment
- '''
- ## Naming stuff:
- ''' functions, variables, and attributes: '''
- lower_undersocre
- ''' protected: '''
- _leading_underscore
- ''' private: '''
- __double_leading_underscore
- ''' classes and exceptions: '''
- CapitalizedWord
- ''' module-level constants: '''
- ALL_CAPS
- ## Misc
- # TYPES, OPERATORS, AND VARIABLES
- # You can use either ' ' or " " for strings, just stick with one
- 'string'
- "string"
- # Concatenate strings:
- 'Hello ' ' world' # >>> 'Hello world'
- 'Alice' * 5 # >>> AliceAliceAliceAliceAlice
- # Get length of a string:
- len(string)
- # Variables are created as you give them value.
- # input function always returns a string so you have to convert it later
- name = input("What's your name? ")
- # Print a string:
- print("Hello there " + name)
- # Or use placeholders
- print("Hello there {0} from {1}".format(name, "New York")
- # Change the separator and strip the newline character
- print("cat", "dog", "mouse", sep="_", end='') # >>> cat_dog_mouse
- # Formatted strings: {placeholder: format_specifier}
- # The general format of the specifier:
- # [[fill[allign]][sign][0][width][.precision][type]
- '{0:#^10}'.format('Anna') # => ###Anna###
- # Allignment > - right, < - left, ^ - center
- # Logical:
- and or not
- # Relational and arythmetic operators are like in C, with the exception of
- 2 ** 3 # >>> 8
- # Comparision operators can be chained
- >>> 1 < 5 < 7 # => True
- # * and + operators create shallow copies:
- a = [3,4,5]
- b = 4*a # => b = [[3,4,5], [3,4,5]]
- a[0] = -7 # => b = [[-7, 4, 5], [-7, 4, 5]]
- # Swap two values in-place
- x, y = y, x
- # CONTAINERS
- ## Lists:
- l = []
- l.append(2)
- # Length:
- len(list)
- l = 'abcdefg'
- # Get last item of the list:
- l[-1]
- # Get first 5 items of the list:
- l[:5] # => abcde
- # Get last 5:
- l[-5:]
- # Copy a to to b
- b = a[:]
- # Point bo to the same list
- b = a
- # is checks if two variables point to the same object, == checks if those
- # objects have the same value.
- a = [1, 2, 3, 4]
- b = [1, 2, 4, 5]
- a == b # >>> True
- a is b # >>> False
- # Check if value is in the list
- animals = ["cat", "dog", "mouse"]
- >>> 'cat' in animals
- True
- >>> 'elephant' in animals
- False
- # Also:
- vowels = ['aeiouyAEIOUY']
- >>> 'A' in vowels
- True
- # Tuples are immutable:
- animals = ("cat", "dog", "mouse")
- >>> animals[i] = "elephant" # => ERROR
- # Convert tuple, or string to a list:
- >>> list('hello')
- ['h', 'e', 'l', 'l', 'o']
- # All sequences can be unpacked into a sequence of variables
- l = [1, 2, 3]
- a,b,c = l # => a = 1, b = 2, c = 3
- letters = 'abc'
- x,y,z = letters
- # Check if list is empty:
- if not l:
- # Do something
- ## Dictionaries
- # Dictionaries map the key to the values. They are not ordered however,
- # so you can't slice them:
- colors = {"red": "#FF0000", "green": "#00FF00", "blue": "#0000FF"}
- >>> colors["red"] # => #FF0000
- # These methods returns iterables
- colors.values() # => #FF0000, #00FF00, #0000FF
- colors.keys() # => red, blue, green
- colors.items() # => ('red', '##FF0000') ...
- # You can iterate over them like:
- for v in colors.values():
- print(v)
- # Or use them to check if sth is in the dictionary:
- >>> "green" in colors.keys()
- True
- # Use list comprehensions to derive one list from another:
- a = [1, 2, 3, 4, 5]
- squares = [x**2 for x in a] # => [1, 4, 9, 16, 25]
- # Filter results you don't want:
- even_squares = [x**2 for x in a if x % 2 == 0] # => [4, 16]
- # Nested:
- a = [-1, 1, 2, 3]
- b = 'abc'
- c = [(x, y) for x in a for y in b if x > 0]
- # It's a little more clear with indentation:
- c = [(x, y) for x in a
- for y in b
- if x > 0]
- # Generator expressions is similiar to list comprehension, but it doesn't
- # produce a list immediately, instead it returns a generator object that
- # produces the values on demand during iteration:
- a = [1,2,3,4]
- b = (x*10 for x in a)
- b.__next__() # => 10
- b.__next__() # => 20
- # Generator expressions are better performence-wise, for example when
- # parsing some text files you don't have to read the entire file at once.
- # Use generator expressions when you only need to iterate over something
- # once, and when the sequence is very large on infinite, otherwise use
- # list comprehensions
- ## Sets
- # Set is an unordered collection with no duplicates
- some_set = {1, 2, 3, 4, 1, 2} # => {1, 2, 3, 4}
- # They use {} to initialize them, but empty set is created like this:
- s = set()
- # Add one element to the set:
- s.add('cat')
- # Add multiple elements:
- s.update(['dog', 'mouse'])
- #CONTROL FLOW
- # If is the same as everywhere
- if a > 10:
- print("Will print this if a > 10 is true")
- elif a > 2:
- print("Will print this if a > 2 is true and the if clause isn't")
- else:
- print("Print this in all the other cases")
- # while loop looks like this, and you can use break and continue in loops
- while True:
- koniec = input()
- if koniec == "koniec":
- break
- # for loop iterate over loops:
- for animal in ["Dog", "Elephant", "Cat", "Mouse"]:
- print(animal)
- # We can use range() function to generate a list of the numbers
- for i in range(0, 10, 2):
- print(i)
- # >>> 0, 2, 4, 6, 8
- # If you want to loop over something like a list of strings, but also
- # need to get the index, use enumerate function
- colors = ['blue', 'red', 'green', 'yellow']
- for i, color in enumerate(colors):
- print('{}: {}'.format(i+1, color)
- # enumerate creates a list of tuples with a string and a number, this
- # instruction unpacks the tuples into i & color
- # You can apply a second parameter to specify where it'll start counting:
- for i, color in enumerate(colors, 1)
- # Use zip to iteratore over multiple iterarators (?) at the same time:
- countries = ['United Kingdom', 'Poland', 'Czech Republic']
- capitals = ['London', 'Warsaw', 'Prague']
- for country, capital in zip(countries, capitals):
- print(country, capital)
- # Zip creates a list of tuples [(countries[0], capitals[0]), ...]
- # FUNCTIONS
- # Declare simple functions with def
- def print_hello():
- print("HELLO")
- # Inwoke them like this:
- print_hello()
- # Functions can obviously take arguments and return values
- def add(a, b):
- return int(a) + int(b)
- # To access global variable inside a function use global keyword:
- a = 10
- def change_a():
- global a
- a = 5
- # If you don't do this, local variable with the same name is created
- def doesnt_change_a():
- a = 5
- doesnt_change_a()
- print(a) # => 10
- # Generator is a function that produces a sequence as a result
- def count(n):
- print('Counting to {}'.format(n))
- for i in range(1, n+1):
- yield i
- return
- # yield is like return, except that it doesn't quit the function
- # The following doesn't execute, instead it returns a generator object
- c = count(10)
- '''
- If the last argument in a function definition begins with **, all
- additional keyword arguments are placed in a dictionary and passed to
- function (useful for configuration options etc.)
- - args i a tuple of positional arguments
- - kwargs is a dictionary of keyword args '''
- def spam(*args, **kwargs):
- pass
- # CLASSES AND OOP
- class Dog:
- ''' Class definition and methods should start with docstrings
- describing what they do '''
- # Class variable shared by all instances
- counter = 0
- def __init__(self, name):
- # Instance variable
- self.name = name
- Dog.counter += 1
- # Local variable, can't be accessed from other methods
- var = 3
- # A static method is an ordinary function that just happen to live in
- # the namespace of the class
- class Foo():
- @staticmethod
- def add(x,y):
- return x+y
- x = Foo.add(3,4) # => x = 7
- # properties are used like attributes, except they're read-only
- class Circle:
- def __init__(self, radius):
- self.radius = radius
- @property
- def area(self):
- return 3.14*self.radius**2
- a = Circle(4)
- a.area # => 50.24
- ''' Instance methods should use self as the name of the first parameter '''
- def __init__(self):
- pass
- ''' Class methods should use cls: (do we use cls like this?) '''
- def __init__(cls):
- pass
- # EXCEPTIONS
- # Catch all exceptions except for those related to program quit
- try:
- # do something
- except Exception as e:
- pass
- # DECORATORS
- # Decorator is a function(for simplicity's sake) that takes a function
- # object as an argument and returns a function object as a return value
- # Decorators are used to add features to original function, in other words
- # they are used to create a function that does roughly the same stuff as
- # the original function but with some additional stuff
- # EXAMPLES:
- # Our decorator:
- def p_decorator(original_func):
- def new_func(name):
- return '<p>{0}</p>'.format(original_func(name))
- return new_func
- # The function we'll decorate
- def get_text(name):
- return 'So your name is {0}'.format(name)
- # We could use this like this:
- my_get_text = p_decorator(get_text)
- print(my_get_text("Albert")) # => <p>So your name is Albert</p>
- # Or even like this:
- get_text = p_decorator(get_text)
- # But Python provides some syntatic sugar, so we apply the decoration before
- # the definition of the function we want to decorate:
- @p_decorator
- def get_text(name):
- return 'So your name is {0}'.format(name)
- # And now we just use
- print(get_text("Andżej"))
- # and there's no way to use the original function without the decoration
- # Decorators can take arguments:
- def add_tag(tag_name):
- def tag_decorate(func):
- def wrapper(name):
- return '<{0}>{1}</{0}>'.format(tag_name, func(name))
- return wrapper
- return tag_decorate
- # And decorations can be stacked:
- @add_tag('div')
- @add_tag('p')
- def get_text(name):
- return 'So your name is {0}'.format(name)
- print(get_text('Antoni')) # => <div><p>So your name is antoni</p></div>
- # BEST EXAMPLE:
- def verbose(original_function):
- def new_function(*args, **kwargs):
- print("Entering", original_function.__name__)
- original_functrion(*args, **kwargs)
- print("Exiting", original_function.__name__)
- return new_function
- # WORKING WITH FILES
- # The builtin function open() opens a file and returns a file object
- # open(filename [,mode [, bufsize]])
- f = open('foo', 'r')
- '''
- File modes:
- - r - read, text mode
- - w - write, text mode
- - a - append, text mode
- - r+ - read and write
- - w+ - read and write, but file is first truncated
- - rb - read, binary mode
- - wb - write, binary mode
- - ab - append, binary mode
- '''
- # Read some data and return it as a string
- f.read(size)
- # Read a line
- f.readline()
- # To read lines from a file you can also loop over the file object:
- for line in f:
- print(line, end='')
- # Writes the conents of a string to the file and returns the number of
- # characters written.
- f.write('This is a test\n') # => 15
- # Redirect the output of print funcion to a file:
- print('The values are', x, y, z, file = f)
- # Good practice: use with keyword when dealing with file object. It makes
- # sure that the file is properly closed.
- with open('file', 'r') as f:
- read_data = f.read()
- # MODULES
- # Best style of importing:
- import random # random.randint()
- import random as rn # rn.randint()
- # After that you can use stuff from random like this:
- random.randint(1,10)
- # You can also just import one function like:
- from random import randint
- # And use it like:
- randint(1, 10)
- # Imports all the definitions in a module except for those starting with _
- # (Avoid this)
- from random import *
- # Check if file is being executed directly or imported as a module:
- if __name__ == '__main__':
- # yep
- else:
- # it must've been a module
- # Get the file path of imported module
- print(random)
- ## SYS MODULE
- import sys
- # Get the number of arguments
- len(sys.argv)
- # The first arg is always the name of the file:
- sys.argv[0]
- # ~ need to get back to this
- # For more advanced command-line handling use optparse
- import optparse
- ## OS MODULE
- # Walking down the path and adding files from subdirs to one list:
- import os
- def get_filepaths(directory):
- file_paths = []
- for (root, directories, files) in os.walk(directory):
- for filename in files:
- filepath = os.path.join(root, filename)
- file_paths.append(filepath)
- return file_paths
- ## REGULAR EXPRESSIONS
- # They're in re module
- import re
- # Match the sequence:
- s = "Hey, my email is ahmm@gmail.com, and what's yours?"
- re.search('\S@\S', s) # => ahmm@gmail.com
- # Extract a match with ():
- match = re.search('(\w+)@(\w+.\w+)')
- match.group(0) # => ahmm@gmail.com
- match.group(1) # => ahmm
- match.group(2) # => gmail.com
- # Gives a lists of all occurences of regex:
- s = "This thing costs $100.00, the other thing costs $50.00, and that one
- is $36.50"
- re.findall('\$[0-9.]+', s) # => ['$100.00', '$50.00', '$36.50']
- # Compile the pattern beforehand:
- pattern = re.compile(r'\w+@\w+.\w+')
- # + and * are greedy by default:
- s = 'The-one-whose-name-cannot-be-spoken'
- re.findall('.+-', s) # => ['The-one-whose-name-cannot-be-']
- # Non-greedy:
- re.findall('.+?-', s) # => ['The-', 'one-', 'whose-', 'name-', cannot-', 'be-']
- # SPECIAL CHARACTERS:
- . # match any character, except for newline
- ^ # start of string
- $ # end of string
- * # match the preceding RE 0 or more times
- + # match the preceding RE 1 or more times
- ? # match the preceding RE 0 or 1 times
- {m} # match exactly m copies
- {m, n} # m to n
- [] # set, examples:
- [AEIOU], [A-Za-z], [0-9.]
- [^5] # match anything but 5
- A | B # match either A or B
- () # extract everything between parantheses
- # CHARACTER CLASSES:
- \d # any digit [0-9]
- \D # non digit [^0-9]
- \s # any whitespace
- \S # any non whitespace
- \w # alhpanumeric [a-zA-Z0-9_]
- \W # non-alphanumeric
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement