Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic" data: integer, float, string, boolean, None "container" data: list, tuple, set, dict "code" objects: functions, methods, classes "custom" objects: defined by Python module authors (including you) VARIABLE: an object bound (assigned to) a name. var = 10 myxx = "hello!" def myfunc(): print('ok!') # int object # str object # function object Initialization of a variable means that the object is being stored in memory for later use during the run of the program. Re-initialization means that the name has been bound to a new object, and is now unbound from the prior object. All initializations create a new binding between a name and an object. STATEMENTS simple statements: assignment (with =): var = 10 augmented assignment (+=, -=, etc.): var += 5 del (unbind a variable or remove a dict key/value): del var break (drop out of a loop): break continue (jump to next iteration of a loop): continue import (import a Python module): import random ternary: an if/else in a simple statement var = 0 if xx < 0 else xx conditional assignment: if/else assignment var = xx or 100 compound statements: if, elif, else: if var > 5: and, or (for compound tests): if var > 5 and var < 10: not (testing negative condition): if not var > 5: while loop: while var < 100:
for: iterate through an iterable (container or file): for item in mylist: try: test code for a raised exception: try: except: lines to execute if exception occurs except IndexError: def: declare a function: def myfunc(arg1, arg2): class: declare a class class MyClass(object): OPERATORS An operator usually has two operands upon which it operates; it returns the result. math operators (+, -, *, /, **, %): var = 5 * 10 concatenation operator (+): var = 'hello' + ', world!' string repetition operator (*) var = 'hello' * 3 binary assignment operators (+=, -=, *=, /=, **=): var += 1 comparison operators (<, >, ==, <=, >=,!=): if var < 20: print var membership operators (in, not in): if 'David' not in names_list: identity operators (is, is not): if var is None: boolean compound operators (and, or): if var > 10 and var < 20: ternary expression (x if C else y): var = 0 if var < 0 else var FUNCTIONS all(): given a container, True if all are True if all([5, 10, 0.9, True]): any(): given a container, True if any are True if any([5, 0, 0, 0.0, None]): bool(): return True or False based on passed object enumerate(): return a list of (count, item) for count, item in enumerate(mylst): exit(): exit the program exit() int(), float(), str(), bool(): object constructors myf = float(5) len(): length of a string or container mylen = len('hello') min(), max(): min or max val from an iterable this = min([5, 9, 3, 0.9, 2]) print(): echo text to the screen print('hello');print('hello', end='\n') range(): return a list of integers in a range myrange = range(5, 10) input(): take keyboard input x = raw_input('enter num: ') repr(): display an object in more 'literal' form print repr(mystr) round(): round a float myr = round(5.539, 2) sorted(): return a list of sorted objects x = sorted([5, 9, 3, 0.9, 2]) type(): get type of any object print type(myr)
INTEGER and FLOAT var = 5 my_xx = 5.0 # initialize an int object # initialize a float object STRING mystr = 'hello' yourzzy = "hello" this_one = """this is a multi-line string.""" # initialize a single-quoted string object # initialize a double-quoted string (same as above) # initialize a multi-line string object count(): return int occurrences of substr within a string mynum = mystr.count('e') find(): return int index position of substr within a string indexx = mystr.index('e') format(): return a new string with {} tokens replaced fmstr = mystr.format(55, 23.0) isdigit(): return True if string is all digit characters if mystr.isdigit(): join(): return a string of element values joined on a str ','.join(['val1', 'val2', 'val3']) replace(): return a new string with substr replaced rstr = mystr.replace('e', 'a') rstrip(): return a str with whitespace / other chars removed mystr = mystr.rstrip() split(): return a list of strs from string split on delimeters slist = mystr.split() splitlines(): return a list of strs comprising lines from file slines = text.splitlines() startswith(): return True if string begins with substr if mystr.startswith('hel'): string slicing: return a portion of string slicstr = mystr[3:5] upper(), lower(): return an upper- or lowercased str newstr = mystr.upper() LIST and TUPLE mylist = ['a', 'b', 'c', 'hello', 5.3, 9] mytup = ('a', 'b', 'c', 'hello', 5.3, 9) # initialize a list # initialize a tuple slicing: return a list or tuple withs elected items newlist = mylist[3:5] subscripting: return one item from a list myitem = mylist[3] list append(): add an item to the end of a list mylist.append(100)
SET myset = { 'a', 'b', 'c', 'd' } =or= myset = set(['a', 'b', 'c', 'd']) add(): add an item to a set myset.add('newitem') difference(): return items in this set not in an iterable newset = myset.difference(this_list) intersection(): return items in this set also in an iterable newset = myset.intersection(a_tuple) union(): return items in both this set and an iterable newset = myset.union(some_set) DICTIONARY mydict = { 'a': 1, 'b': 2, 'c': 3 } add a key/value pair mydict['d'] = 4 read a value based on a key var = mydict['d'] loop through a dict's keys for key in mydict: loop through a dict's items for key, val in mydict.items() check for key membership for key in mydict: return length of a dict thislen = len(mydict).get(): return a value (or default) given a key value = mydict.get('a', None).items(): return a list of 2-element tuples items = mydict.items().keys(): return a list of the dict's keys keys = mydict.keys().values(): return a list of the dict's values values = mydict.values() FILE fh = open('thisfile.txt') # initialize a file object function: open() a file for writing fh = open('thisfile.txt', 'w') function: open() a file for appending fh = open('thisfile.txt', 'a') method: write(): write string data to the file fh.write('a line of text\n') 'for' looping: assign each line in file to a 'control variable' for line in fh: read(): return a string containing the text of the file text = fh.read() readlines(): return a list of strings, each line from file lines = fh.readlines()
MULTIDIMENSIONAL CONTAINERS list of lists x = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] o access a single element item = x[1][2] # 6 list of dicts o loop through for innerlist in x: for item in innerlist: print item x = [ { 'this': 5, 'that': 10 }, { 'this': 20, 'that': 7 } ] o access a single element value = x[1]['that'] # 7 dict of lists o loop through for innerdict in x: for key in innerdict: print innerdict[key] x = { 'a': [ 1, 2, 3, 4 ], 'b': [1, 3, 2, 4] } o access a single element item = x['b'][1] # 3 o loop through for key in x: for item in x[key]: print item dict of dicts x = { 'a': { 'this': 5, 'that': 10 }, 'b': { 'this': 20, 'that': 25 } } o access a single element o loop through value = x['a']['that'] # 10 for key in x: print key + ':' for ikey in x[key]: print ' ' + ikey + ', ' + str(x[key][ikey])
CONTAINER OPERATIONS (applies to list, tuple, set, string, others) len(): get int length of (# of items in) container length = len(mylist) in: test for membership in a container if 'hello' in mylist: for: loop through each item in a container for item in myset: sum(): sum values in a container (numbers) total = sum(prices) max(): get max value in a container highest = max(prices) min(): get min value in a container minim = min(prices) sorted(): return list of items, sorted slist = sorted(mylist) subscript: return item at index pos (list, tuple) first = mylist[0] slice: return new container with selected items newlist = mylist[3:5] LIST COMPREHENSIONS wanted_lines = [line.split()[1] for line in lines if line.startswith('1972')] LAMBDAS slist = sorted(mylist, key=lambda x: x.split()[0]) CUSTOM SORT FUNCTIONS def by_first_item(line): items = line.split() first_item = items[0] return first_item slist = sorted(mylist, key=by_first_item) TRAPPING EXCEPTIONS try: x = int(input('enter a number, please: ') except ValueError: print('oops, that did not convert to an int!')
USER-DEFINED FUNCTIONS def addthese(arg1, arg2): mysum = arg1 + arg2 return mysum argument and return value def myfunc(this_arg): new_val = this_arg + 1 return new_val positional arguments def myfunc(arg1, arg2): keyword arguments def myfunc(this=none, that=0): arbitrary arguments: *args def myfunc(*args): arbitrary keyword arguments: **kwargs def myfunc(**kwargs): MODULES time: import time time.sleep(10) date and datetime: from datetime import datetime dt = datetime.now() timedelta: from datetime import timedelta td = timedelta(hours=3) USING MODULES import modname: import a module's variables through its name import mymod print mymod.var import modname as convenientname: rename module in our code import mymod as tt print tt.var from modname import varname: import a variable from module from mymod import var from modname import *: don't ever do this! ;) NO sys.path: module search path sys.path.append(newdir) PYTHONPATH: environment variable informing the sys.path if name == ' main ': module / script "identity gate" if name == ' main ': main() pip module install program
CLASSES class declaration class MyClass(object): pass set object's attributes ( dict ) x = MyClass() x.var = 5 get attribute value print x.var self implicit argument to method def dothis(self): init constructor def init (self): EXCEPTIONS (also see Exceptions Reference) SyntaxError: when the code has a syntax mistake (missing paren or quote, etc.) NameError: when a variable name is used that doesn't exist (often a misspelling) TypeError: when the type of object used in a function or method is incorrect AttributeError: when attempting to acces an attribute (e.g. method) that is incorrect for the object IndexError: when attempting to access an item in a list where the index doesn't exist UnboundLocalError: reading a local variable before def dothis(): assigning x = x + 1 # is x a global? IndentationError: when an indent occurs before for item in mylist: a block, or doesn't occur inside a block print item raise: cause an exception to occur raise ValueError