# pythonFeatures.txt # author: Dave Renner # 07/14/11 1915 # Rev: 09/24/12 STRUCTURE 1) Typing: Python is loosely-typed, unlike C. Functionality not data-type-centric; it is 'interface'-centric, sort of like C++ templates or 'generic' programming 2) Self-Referentiation: Python is extensively 'self-referential'. It is structured so that its design is viewable and modifiable (that is, 'extendable') by the programmer. 3) Object-Oriented: Python self-referential structure is designed with the object-oriented paradigm and syntax. All meta-data in Python are objects, such as programming modules, functions, names, etc. Similarly all variables -- both built-in and user-defined -- are objects. 4) Classes: Programmer need not use O-O 'class' structure in his/her programming, tho many facilities are provided in Python by class objects 5) Classes: In Python, 'class' isn't just a declaration or definition, as in C. It is a statement, and it creates an object which is a class, NOT an instantiation of a class, but the class itelf. A 'class' statement is referred to in Python as a 'class factory'. SYNTAX Continuation Backslash or parens List or tuple needs no line continuation char Alternate: any grouping by parens Inclusion Functions and blocks are defined by uniform indentation, not by enclosing marks NAMING __init__ Names prefaced and followed by two underscores have special meaning to the Python interpreter. Usually 'operator 'overloading' methods. (See OPERATOR OVERLOADING) _var Begin Underscore: Assigned at top level of module are not copied in 'import_from'. Pseudo-hiding __myName Begin two underscores: Local to its class; names mangled to include class name. Its position would make it local anyway,but mangled name ensures no name conflicts MyClass Convention for class name my_func Convention for function name SCOPE, NAMESPACES, VARIABLES, ASSIGNMENT Objects, Variables: # 'Object': aka variable or attribute, which may be defined # synonymously. Technically a class function, tho treated as an 'object' # may be thought of as an 'attribute' (more properly, a 'behavior'), # tho it's not considered a C-like 'variable' -- even though # functions, like almost everything else in Python can be changed, # giving them, essentially, a 'variable' nature. # All these definitions are concepts which have similarities to, but # not analogous to, the same terms in C or Java... Scope: # Scope = Namespace. Namespace contains objects # Scope is search order for unqualified variables Scope: 1) Local function 2) Enclosing function 3) Global module 4) Python built-in 5) lambda (see CALLBACKS) Variables: # Variables are created and assigned simultaneously. Variables may be defined by: 1) myVar = 5 # usual way 2) for i in myList # 'i' is created as a temp variable 3) import myMod # myMod is like a copy of the imported module. # Objects within myMod, if mutable, # may be modified but only for the scope # of the importer 4) Class MyClass # creates myClass object, though NOT an instance # of that class 3) def myFunc # creates function object and initializes all # variables within Classes & self: # 'self' is an attribute not a variable; it doesn't vary, and not # thought of as an object. It is an attribute of an instantiation # of a class, to refer to itself. # It is useful in many concepts where the object name is not known. # It is also required in a class function def, as the first parameter, # (tho technically, it's only the position that's req'd, not the name # 'self' MODULES & IMPORTS Defin: Module is source file of Python code Import: Scope: Can be either module or object within module Import: Define: 'Import' actually means to run the code Import: When: modules may be imported only once per process Import: from: myMod import myVar. From then on, myVar need not be qualified. 'from' copies module object into importer, whereas import without from treats the imported module as an object reference. 'from' object modifications, then, do NOT affect the imported module namespace. Import: from: myMod import * doesn't import names begin with underscore Here myMod may be a pathname, and * imports all files in that directory Import: All: Objects within imported file can be restricted by Python kludge: if '__init__.py' file contains'__all__ = [ this, that ]' ONLY the variables 'this' and 'that' will be imported. '__all__' here is treated specially by Python interpretor. (See NAMING). If not defined specifically here, '__all__' serves as a module variable that may be overridden. It is not discussed in textbooks because its default meaning is intuitive. Import: Reload: module can be reloaded after 'import', but not (successfully) after 'from' import. If imported module has been modfied, if reloaded, the new values will appear. Without 'reload', a subsequent import will have no effect, since a module can be imported (and run) only once. Import: As: import...can be used to provide short-name alias for complex imported file package name. DATA TYPES -- GENERAL Collection Non-Python (my) term for multiple elements or objects in one grouping, like a 'C' aggregate type. Lists, tuples, sets, and dictionaries are collections. A collection may nest other collections, up to multiple levels Element Member of any collection Object (my) term, usually referring to a variable (or constant), but in Python may refer to any 'noun', including a function or module Module Python 'executable' (interpret-able) file, either runnable (containing a C-like 'main' equivalent) or like a C compiled 'object', not executable in itself Iterable Collection of values (that can be traversed): list, set, string, tuple, or file Sequence Collection of values that may be accessed by index Mutable Any object that can be modified; can apply to any Python type Ordered Pair Collection of pairs. The first element of each pair is a lookup key, which may be of any non-mutable data type, such as an integer or string. AKA 'Mapping' Reference Alias or 'pointer' to object, not a physical copy. Python uses 'object references' extensively; this is how parameters are passed to functions DATA TYPES, SPECIFIC # Data types are undeclared in Python, but they do exist, and are # defined by syntax. They're only evident on creation # of a specific variable, which is only done by assignment, # not declaration or definition, as in C Partial list: Integer 5 Decimal 5.55 Hex 0x9ff Octal 0o177 String Non-mutable, iterable array of characters in quotes 'my string' "r'my string'" will keep any embedded backslashes without translation (raw) List Mutable, iterable collection of comma-separated items, not always of the same type, in [] [ 1, 2, 3, 'one', 'two', 'three' ] Tuple Non-mutable, iterable collection of items, in () ( 1, 2, 3, 'one', 'two', 'three' ) Dictionary Mutable collection of ordered pairs or mappings (key: value) in {} or typename 'dict'. Can be used as 'record' or C 'struct' # this dictionary maps each food item string # to a breakfast menu item number { 'spam' : 45, 'eggs' : 32, 'spegs' : 45 } Set Mutable, iterable sequence of unique values each of which is immutable (like integers, strings, or tuples) supporting math operations union and intersection File Persistent object for input or output, created by OS thru Python 'open' call. Is first-class type in Python None Special data type representing False. Can be used to create and initialize lists, for example Bool Special data type. Actually a subclass of int. 'True' and 'False' are the sole instances of bool. More intuitive than int 1. Example: 'while True:' DICTIONARIES 1) Contents: Arbitrary objects; keys need not be of same type (though they usually are) 2) Structure: Mutable 3) Structure: Key/value pairs. Items stored and fetched by key. Key is immutable: string, number, tuple 4) Structure: Unordered hash-tables; quick lookup; no sequential operations, no indexing 5) Scope: Supports nesting of other arbitrary objects, including dictionaries 6) Advantages: Versatile; frequently used within Python language itself 7) Creation: May be quickly populated by lists using 'myDic = dict(zip(keys, vals))' 8) Combining: Dictionaries may be combined into a dictionary of dictionaries. This is common in Python. 'id' of dict. may be used as key, name of dictionary as value. Example: myDicts = {id(names):'names', id(addr):'addresses'} 9) Storage: Dictionaries are often used for quick storage. Used in functions called frequently for quick results, where this result may have been already computed STRINGS 1) Overview: Many string operations -- see below 2) Constants: String constant escape chars, like C: \n, \\, \', \", \b 3) Formatting: Formatting codes, like C, though different syntax 4) Formatting: Codes: see PRINT 5) Formatting: Syntax: woman = 'loretta' badger = 'tim' print 'My name is: %s, but some call me %s' % (woman, badger) 6) Methods: Strings are objects in Python, and thus have methods associated with them,(not functions, which have no object to be applied to). (See STRING METHODS) 7) Caveat: Creation: Strings cannot be changed, so s = s[1:3] creates a new string with a new Python ID, using the same name as the old string, so the old string is no longer accessible by that name 8) Internationalization: Unicode char set represents all languages. It is 16 bits per char. Python provides Unicode conversion 9) Immutability: Cannot change string, but may add to it and save it under same name! Just can't change string 'in place' FILES 1) Persistent 2) Mutable by default 3) Input or Output or both 4) Creation Anomoly: not by assignment but by Python 'open' function 5) Permissions specified by file modes, as in C 6) Iterable by line 7) Attributes: (Object-oriented syntax): name, mode, closed OPERATORS # The usual C-like operators: +, -, *, etc. Not-so-standard, but # still C-like. # Numeric 'operators' include type conversion functions (below) # 'Operators' need not be symbols, but can have appearance of # function calls # Operators may be overloaded. (See OPERATOR OVERLOADING) x = y assigns value of y to variable x. This is an object reference, not a memory copy!. x == y equality test, like C x != y inequality test, like C x**y exponentiation, x to the power of y x or y logical OR; y is evaluated if x is false x and y logical AND; y is evaluated if x is true not x logical negation x in y membership. x is/is not contained in set y. x must be separate element, not part of embedded element x not in y x | y bitwise OR; union x & y bitwise AND; intersection x^y bitwise EXCLUSIVE OR x << y x left-shift by y number-of-bits ~x bitwise inversion x - y return x minus y x + y return x plus y. Creates new result; does not concatenate to object (if used with strings or lists). This is a concatenation operator and may be used with non-numeric objects like strings. It is not as efficient as in-place methods applied to non-mutable objects, like myTup.append(), because it must create a new object x +=y automatic concatenation. More efficient. Python actually performs operation in place (like a list.append()) instead of creating separate temp objects (like x = x + y) x % y return modulo (remainder after division of x by y x / y divide x by y; remainder saved for decimals, not saved for integers x // y divide x by y; remainder not saved x[0:100:10] slice set of values by index, starting at first index, ending at 100,incrementing by 10 each time x == y tests if x is equal in value to y x is y tests if x is same object as y INDEXES # Certain collections -- list, tuple, set, string -- are iterable, # that is, their elements may be stepped through (usually) one # at a time # Each element is accessible by an index or offset from the beginning, # beginning with index 0 (as in 'C') # Index is sort of an operator. It returns a value 1) Last Item: -1 index denotes last item 2) Slice: boundaries default to 0 and sequence length, so [4:] will start at index 4 and continue to the end (len - 1) [:5] will start at beginning (index 0) and continue through index 4 [:] will include the entire sequence, so it will make top-level shallow copy(won't copy collections contained within this list; just provide references) [:-1] will reverse entire sequence (kludgy syntax) 3) Negative Indexing: -1 = last element, -2 = second-to-last elem 4) Nested Tuples (matrix). tp = [ [1,2,3], [4,5,6], [7,8,9,0] ] tup[-2, -1 ] = 6 5) Add to beginning of list: L[:0] = 'nowfirst' 6) Add to end of list: L[len (L):] = 'nowlast' 7) Remove item from list: L[5:6= = [] 8) Insert item from list: L[5:5] = 'inserted after index 5' 9) Modification of list in 'for loop': see 'STATEMEMENTS -- CONDITIONALS' ITERATORS # Iteration is done by means of control statements, so iterator is # like an operator, too # 'in' operator gets all elements in data type. Each data type has its particular type of element string -- each character list -- each element tuple -- each element file -- each line dict -- each key Example: for line in filename # file object is iterable by line for x in myList # x is single element in list, string, # or tuple for k in myDict # for each key OBJECT COPYING Deep Copy vs. Shallow Copy: 1) Deep copy: true copy, creating new memory areas. 2) Shallow Copy: creating references, or aliases. 3) Implementation: Python copies lists and tuples by creating new memory (deep copy) for the first level of a list/tuple only when using index notation [:]; 4) Nesting: any nested levels are shallow copies (by default) 5) Nesting: Implementation: For nested tuples, copy.deepcopy() must be used to copy all levels. 5) Implication: by default (using shallow copy) if changes are made to top-level items of a copied list, they do not affect original list 6) Implication: if changes are made to a nested level of a copy, they will also be made in the original. # # Simple Copy: syntax L1 = L2 -- any assignmemt using '=' -- # makes a reference only for a list copy Copy and Re-Order: Reordering while copying can be done simply by converting a tuple to a list, re-assigning while doing so: [ a, b, c] = (1, 2, 3) # original order [ c, a, b] = (1, 2, 3) # re-order # See LIST OPERATORS -- FUNCTIONS FUNCTIONS Defin: Functions are defined by 'def' statements Params: Parm args are not copies as in C; they are not pointers as in C; they are object references which act like either copies or pointers, depending on their mutability Params: Keyword parameters must follow default positional parameters Params: Mutable objects: should either copy param, modify copy, and return copy or pass in a copy. List copies may be created using index sequence. Example myFunc(myList[:]) Default: Parm args can be defaulted by key-value pairs (keywords). If so, they must be listed after all non-keyword args. From that point, they may be specified (by caller) in any order, by full expression (key2 = 'three') to override default Keyword: Keywords, including defaults, are local to function during its lifespan, making them like C-static to the function. If mutable, they may be modified and their modified value will persist Return: Functions may return multiple values in the form of an implied tuple Implied: see CALLBACKS FUNCTIONS AND OPERATORS 1) Intro: Python uses both symbols and words for some operations. 2) Scope: There are many operators / operations applying to different data types, most of which use symbols, but some of which use text words 3) Operators: Provide intuitive functionality and are based on fundamenetal arithmetic operations 4) Collections: Strings, lists, tuples, etc. can have operators (unlike C), where they make sense. These may be regarded as 'functions', but operators are really functions, too 5) Types: Operators may include type conversions (see TYPE CONVERSIONS) 6) Class Operators: There are also Python class methods (using O-O Python) that can do operations on non-numeric objects. These can be overloaded. (See 'OPERATOR OVERLOADING'.) Examples are: __contains__, __iter__, __getitem__, __len__ 7) Built-Ins: More commonly-used are Python built-in functions (see BUILT-INS) like len(), and index operations STRING / TUPLE (NON-MUTABLE) OPERATIONS len(s) length of S, whether it be string, list, or tuple min, max(s) find minimum or maximum value in string, list, etc. MUTABLE OBJECT OPERATIONS # Lists and dictionaries support above 'non-mutable object' operators # as well. Some of them may be classified as functions: 'del', 'len', # and 'frozenset' since they are general Python functions (below). # All of them can be created by type conversions (below) LIST OPERATORS / FUNCTIONS S[i] = X assign value X to position i of string-or-list object S del S[3:6] delete items from indeces 3, 4, 5 L2 = L1 make shallow copy (reference or alias). See INDEXES and OBJECT COPYING L2 = L1[:] make physical copy (new memory area) for one level deep; references for deeper levels L1 = ' ' * 3 make list L1 by making three copies of blanks. Good way to initialize a list. Multiplier must be int, not dec L1 + L2 list concatenation. This creates a new, temp list, whereas S1.append(s2) modifies list in place DICTIONARY FUNCTIONS D['name'] get value of key 'name' in dict 'D' k in D key membership test del['name'] delete key-value pair of key 'name' TUPLE FUNCTIONS () create an empty tuple (6,) create a one-item tuple. (Trailing comma, not parens, defines a tuple) (3,5,6) create 3-item tuple t = 3,5,6 create 3-item tuple 3,5,6 = t unpack tuple into component items This is a way of creating C-like 'enum' T1 = T2 create a shallow copy. If multiple layers exist, only top layer will be physically copied; others will only be referenced T= = '0' * make tuple T by making three copies of Zs. Like list. Multiplier must be int, not dec SET FUNCTIONS { 's', 'p', 'a', 'm' create a set of four unique letters. Curly braces look like dictionary, but there are no key-value pairs {ord(c) for c in 'spam'} create temporary set of each letter of the word 'spam' frozenset( range (1,5) ) create an immutable set of integers of values 1 to 4 set1 - set2 create new set: items in set 1 that are not in set 2 set1 | set2 create new set of items in either set1 or set2, no duplicates len(set) find number of items in set FILE FUNCTIONS # 'open' is the only function. It returns a file object, # which performs object methods (See FILE METHODS) open("myfile.txt", r) opens file for reading only METHODS Intro: Python supplies functions to operate on various (most) Detail: Python 'objects' are truly object-oriented, however, so enclose methods (not functions) Syntax: Each of these methods follows syntax: 'myList.append(x)' Example: O-O programing examples appear in my 'pyDemo.py' demo Overloading: Python has many Operator Overloading methods, most of which aren't used in non-esoteric programming Overloading: Class methods aren't overloaded by signature, as in C, because types are not explicit in Python STRING METHODS encode convert standard string to another format (like Unicode) and Unicode to std find ( substr, optional start offset, opt. end offset ) rfind ( substr, opt. start off, opt. end off ) startswith ( substr, opt. start off, opt. end off ) endswith ( substr, opt. start off, opt. end off ) count (subst, start, end) counts occurrence of substr in range join concats two strs. Efficient to join " " w/ str to convert list to str. Also takes second object and converts it to string. Example: 'STR'.join( [ 'eggs', 'spam', 'ham' ]) split ( delimeter, opt. max nbr of splits ) splitlines split string into separate, delimiter-broken lines replace ( oldstr, newstr, opt. nbr of times ) lstrip ( opt. chars. Whitespace if not specified ) rstrip ( opt. chars. Whitespace is not specified ) isslpha test if char is alphabetic isdigit test if char is digit isspace test if char is space, multiple spaces, or tab upper convert to upper case lower convert to lower case LIST METHODS index( x[ , i[, j]] ) return first item of value x in list. if i and j are given, x must be between values i and j append(x) add object to end of list. This, and 'extend' method, do not create a new object, like concatenation operator (plus sign) does, so 'append/extend' are more efficient extend(x) add list of items 'x' to end of list insert(i,x) insert object x into list at offset i. If i is negative, will insert at front of list (unlike list find operations) remove(x) delete first-found item x from list pop(i) delete item i from list. If i = -1, removes last item that was appended sort(func) sorts list using func provied by programmer. This modifies orig value of list. Calls Python's 'cmp' function. Example: # mySortFunc must always take two parms # indicating two items to be sorted # (supplied by Python iteravely when # sorting the list), then call 'cmp' function # with each item, then return result. # Python does the rest by magic. myList.sort(mySortFunc) # this modifies a standard sort by converting # each item to lowercase first. In other words, # it's a case-independent-sort # def mySortFunc(one, two): myOne = one.lower() myTwo = two.lower() result = comp(myOne, myTwo) return result reverse() reverse order of all items in list count() find number of items in list DICTIONARY METHODS items() return all key-value pairs in dictionary copy() return shallow (one-level) copy of dictionary. Full copy, though, as opposed to assignment D2 = D1 update(D2) merge dictionary D2 into calling dictionary setdefault( key, defaultvalue) set default key pop(key) return last key-value pair of 'key' that was appended; deletes it from dictionary K = D.keys() gets keys K.sort() sorts dictionary. 'key' is the object, not dictionary values() get all values from dictionary. Not often used. has_key(K) determines if dictionary has key K TUPLE METHODS # these are the only methods available for a tuple index( x[ , i[, j]] ) same as list method; return first item of value x in list. If i and j are given, x must be between i and j tup1.count() get number of items in tuple SET METHODS set1.issubset(set2) test if every element of set1 is in set2 set1.symmetric_difference return new set with elements in either set1 or set2, but not both set1.update(set2) add items in set2 to set1 set.clear() remove items from set FILE METHODS # methods are performed by file object (the return value # of file 'open' function) # Mode: Unix-like r, r+, w, r+, a, a+ # Binary: rb = read binary file. Default is text read() read entire file into one string. Text file end-of-lines translated to \n read(n) read up to n bytes readline() read up to end-of-line char. Usually used in file iteration (for lines in file readline()) readlines() read entire file into list of line strings write(S) write string S to file. For binary file, may write non-ASCII chars writelines(S) write all strings S to file. No newlines. To add newlines,just 's + "\n" for s stringlist' close() close file. For efficiency, but not required tell() return file's current posit seek(offset, whence) go to offset posit in file. whence: 0 = begin, 2 = end, 1 = current pos (+ or - offset) flush() write to disk OPERATOR OVERLOADING 1) Intro: Python's inherent object-oriented design provides text-style 'operators' 2) What: These operators can be substituted for traditional symbol operators. 3) Where: Can be applied to various data types, each of which is Python 'class' 4) Why: Usually to overload (augment) basic or intuitive functionality of operators 5) Syntax: Two leading underscores 6) Xplan: Some of these would not intuitively be considered 'operators' but they are listed as such in Python definitions 7) Implic: Variables or objects or attributes may be created having the syntax of overloaded operators (leading and following double underscores). The specially-interpreted variable __all__ as used with the 'module' object can be viewed as one of these, since it is not explicitely defined as an overloadable operator in Python. (See MODULES) All Types (partial): __new__ as a constructor __init__ to create instance variables __del__ as a destructor __str__ returns user-friendly string of 'self' object __format__ formatted string represent of object __hash__ used on dictionaries, which have hash order __call__ when instance is called like a function __setattr__ dynamically sets attributes __getattr__ invoked if its param is undefined __lt__ less than. Comparison order can be modified here __le__ less than or equal to Collections (Sequences and Mappings) __len__ length __contains__ is in __iter__ returns iterable object with accomp __next__ method __next__ returns next item in iterable sequence __getitem__ returns item in mapped object by key. __setitem__ sets value of specified key in mapped object __delitim__ deletes key-value pair in mapped object Arithmetic __add__ may be applied to non-number objects. Also __sub__, __mul__, __div__, __mod__ __and__ boolean and. Also __xor__. __or__. Not used in bit operations __divmod__ returns tuple of quotient, remainder __floor_div__ math only __lshift__ left-shift. (Wouldn't be modified...). Also __rshift__ __pos__ convert to positive __pow__ exponentiation __index__ makes object usable as index TYPE CONVERSIONS 1) Define: Type Conversions are functions that convert one type to another. 2) Scope: Some are more useful than others. 'dict' conversion, for example, is a good way to create dictionaries. 3) Set: 'set' conversion is usually required to deal with the 'set' data type, since data is rarely defined, initially, as a set 4) Collections: Type Conversions are always required to concatenate aggregate types, like tuples and lists when using math and index operators. 5) Except: Certain functions and methods do not require type conversions. Partial list: ord(C) convert single char to int chr(I) convert int to single char int(x) convert x to integer hex(x) convert x to hexadecimal int oct(x) convert x to octal int float(x) convert x to float str(x) convert x to string. Will be printed in quotes list(1,2,3) convert collection to list. Usually superfluous. Will be printed in [] tuple(1,2,3) convert collection to tuple. Usually superfluous. Will be printed in () tuple('myT') convert any iterable (collection) to a tuple dict(name = 'Bob', age = 45, job = ('mgr', 'dev') create dictionary by adding 'fields'. This dictionary represents one 'record' dict ( [ ['a', 1], ['b', 2], ['c', 3] ] create a dictionary by a list of key-pair lists set() create an empty set set(mySet) create copy of mySet BUILT-INS # Many of these call functions listed in OPERATOR OVERLOADING section. # Others cannot be overloaded. # Many of these can be used in looping ('for') iterations # over collections (lists, tuples, dictionaries) # Partial list. Some of these are discussed above abs() return absolute value all(ITERABLE) return True if all elements of ITERABLE are true any(ITERABLE) return True if any elements of ITERABLE are true chr(I) convert integer to character dir(object) lists names in current object scope. Useful for introspection or testing, often outside the program itself filter( function(), ITERABLE) return those elements of ITERABLE for which function returns True id(object) return the unique ID of object iter(ITERABLE) returns iterable object with accomp. 'next' method input("prompt") display "prompt" and accepts user for keyboard input len(object) return object length. This is ubiquitous max(ITERABLE, *arg, key) for ITERABLE, return largest value of argument or arguments. Optional arg 'key' is name of value transform function (like a progammer-supplied sort funcion) map(ITERABLE) perform a function for each element of ITERABLE. In same family of functions as 'filter'. map (myFunc, myTuple) min(ITERABLE, *arg, key) (see 'max' above) next(ITERABLE) returns next object in iterable sequence open('finename.dat', r+) (see 'FILES' section) ord(C) convert character to integer print('string') (see PRINT section) range(start, stop, step) select elements of a group within a range of start to stop, incrementing by step round(X, n) round integer X to n digits sorted( ITERABLE, key=None, reverse=False ) return a new sorted list from items in ITERABLE str(object) convert object to string zip( ITERABLE, ITERABLES* ) return a series of tuples where each Nth tuple contains the Nth element from each of the argument iterables Example: for: list1 = [1,2,3,4,5] list2 = ['one', 'two', 'three', 'four', 'five'] zip( list1, list2 ) the result would be [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four'), (5, 'five')] 'zip' can be used to create records GENERATOR EXPRESSIONS Generator expression creates a temporary list used as input to a function Example: 'myOrds in (ord(x) for x in myString if x not in mySkipThese)' 1) Read list/tuple 'mySkipThese' to get digits to be excluded for processing 2) Read (iterate) 'myString' of single-digit characters, processing only those not excuded 3) Convert each of these chars to a digit 4) Append each to list 'myOrds' CALLBACKS Callback: A 'callback' is a function that is defined but not used immediately or explicitely within the module's code. Its detailed functionality can generally only be performed by the defining module, tho. A callback often created for use by another module; often in a GUI or otherwise O-O context, like an action to be performed when a button is pressed. The module which defines it often doesn't know who will call it. Its address (in Python, the function object) must often be passed to a non-local caller. lambda: 'lambda' operator can be used to define unnamed, in-place functions without overhead of a 'def'. Often used when function name must be passed as argument to a callback routine Example: lambda arg1, arg2: return arg1 * arg2 bound objects: Class methods are often used as callback functions. If so, however, they must be bound to an instantiated object. There is no function or 'class' (not instatiated class object) scope, as in C. Example: obj1 = SpamClass() myB = obj1.spamMethod # Here, 'myB' may be passed as a function in a callback PRINT 1) print() -- Python built-in function. Works on multiple objects (like 'len' and '+') 2) Format: flags, width, type, precision Example: %0f4.2 3) Flags (partial): 0 pad nbr with leading zeros + begin nbr with pos or neg sign 3) Types (partial): d long integer i long integer f floating point u unsigned int or long o octal x hex 4) Precision: dot, followed by nbr of digits after decimal 5) Print to file: print >> myfile.txt, myTextLine 6) Print is Python function for: import sys sys.stdout.write( str(x) + '\n' ) 7) Redirection: Since print used object 'stdout' and method 'write', it may be overridden by overriding stdout (as in Linux). If stdout is redirected to a file, the 'write' method will be the one implemented by file objects. Very streamlined! Example: import sys sys.stdout = open('log.txt', 'a') # will show up in log file print x, y, z STATEMENTS & EXPRESSIONS # Defin: statements define things; statements are not expressions # Defin: expressions are arithmetic-like calculations to be evaluated # Examples given in my 'pyDemo.py' demo # Statements are not functions, so usually no following parens PURPOSE function name DEFINE FUNCTION def may appear anywhere in module; inside and outside classes NAMESPACE DECL global CLASS DEFIN class DELETE OBJECT del INCLUDE FILE import, import from DO exec exec('string') performs Python function. It's used when concatentating strings to form a function call; the end result of the concat is not a pointer to the function, just a string. Example: modname = 'myMod' exec ("import" + "modname") DO eval computes an expression defined as a string. Similar to 'exec', but used with expressions, not function calls. Example: word = 'xo' z = eval( 'word * 10') print z DISPLAY print CONDITIONAL while This is not nearly as efficient as 'for' CONDITIONAL if, then, else: CONDITIONAL for my_Target in IterableOrCondition: CAVEAT: DO NOT MODIFY-IN-PLACE ITEMS IN A SEQUENCE WITHIN A LOOP. PYTHON DOES NOT DO IT CORRECTLY! INSTEAD, COPY THE SEQUENCE AND MODIFY THE UNNAMED COPY! EXAMPLE: for x in s[:] if x == 0: remove(x) (THIS IS JUST AN INDEX SPECIFICATION) CONDITIONAL continue, break JUMP return NULL pass DEBUG try...except...finally DEBUG assert DEBUG with Wraps block in a Context Manager, which ensures that final condit is run. Alternative to try...finally EXCEPTIONS See my test 'xcept.py' SYS # sys is a Python standard library module which contains objects and # functions (mostly objects) List of interpretor-related exported objects (partial): argv Command-line argument strings byteorder Return native byte-order (big for big-endian) exit(n) Quit the program path List of strings used for the module search path. This may be modfied in Python using OS's native path convention. Example: 'sys.path = [r'd:\temp'] prefix Assign a string giving the site-specific directory prefix stdin Standard input stdout Standard output stderr Standard error time time.start() gives current time OS # os is a Python standard library module which contains objects # and functions OBJECTS environ List of environmental variables. os.environ['USER'] returns USER FUNCTIONS Environment Tools: getcwd() Get current working directory chdir(path) Change directory uname() Get system name Shell Commands: system(cmd) Execute OS command, like 'dir' popen('fn','r') Open file using stdin and stdout as IO File Pathname Tools: chmod(path,mode) Change file capabilities (r,w,x) chown(path,uid,gid) Change file ownership link(src,dest) Hardlink file listdir(path) List all entries in directory 'path' mkdir(path) Create a directory rmdir(path) Remove directory stat(path) Return file size, owner, date, etc. symlink(src,dest) Soft-link file walk(topDir, topdown=True, onerror=None, followlinks=False Generate filenames in a directory tree Process Control: abort() Stop process execv(path, args) Execute new program after new process is forked fork() Spawn a new process. (Unix/Linux only) getpid() Get process ID kill(pid, signal) Send signal to process OS.PATH # os.path is a Python standard library module List of systems interface functions (partial): basename(path) return absolute path only from fullpathname dirname(path) return directory of file name from fullpathname isdir(name) returns True if name is a directory isfile(name) returns True if name is a file INTERNET & XML MODULES AND TOOLS # This module uses O-O programming Partial list: socket() create socket select() wait for activity on sockets http.client() http, nntp, and telnet protocol implementation ftplib.ftplib() processes file transfer protocol urllib.urlopen() connects to url urllib.urlparse() splits url into component parts urllib.request() fetch web page xml.parsers.expat module to parse SAX-like XML xml.sax module to process SAX XML MATH MODULE List of functions (partial): ceil(X) ceiling value of X (round up) floor(X) floor value of X (round down) log(X) natural logarithm of X (base e) cos(X) cosine of angle X degrees, unit circle tan(X) tangent of angel X degrees, unit circle MISCELLANEOUS MODULES # for portable SQL database API, see my 'pyDemo.py' demo time Date/time processing (See 'pyDemo.py' demo) datetime Additional Date/time processing (See 'pyDemo.py) random Random number generation bisect Functions for manipulating sorted lists threading Interface to _thread functions class copy Supplies 'deepcopy', to physically copy all layers of a collection signal Unix-like signal-handling functions string Additional string-handling functionality re regular-expression handling shutil shell utils, like copy2(src, dest) copies file data & stat info tkinter GUI-module building pickle Persistent-object creator struct Building of C-struct-like objects