-
naming
- underscore/letter, then letters, digits or underscores
- case-sensitive
-
reserved words/keywords
-
Subtopic
- Subtopic
-
description
- An interpreted, bytecode compiled language. The bytecode is cached. It features dynamic typing and optional object orientation.
-
running
-
an interactive shell
- Subtopic
- To return to the outermost block, hit the carriage return on a blank line.
-
expressions are automatically echoed to the console
-
example
- Subtopic
-
from scripts
- stored in .py files
- expressions are not automatically printed to standard output
-
blocks
-
determined by indentation
-
example
- Subtopic
-
statements
- no termination character
-
comments
- begin with "#"
-
operators
-
assignment
-
Subtopic
-
multiples allowed
- Subtopic
- Subtopic
-
compound assignment
-
Subtopic
- works on many datatypes, including Strings
- -=
- creates references
- names created when first assigned
-
equality
- ==
-
modulo
- %
-
used to inject values into strings
- Subtopic
-
with a tuple:
- "One: %s Two: %s" % (1, 2)
-
with a dictionary:
- "One: %(two)s Two: %(one)s" % {'one': "1", "two": 2}
- mathematical
-
native data types
- Integers
- Floats
-
strings
-
delimiting
-
delimited by "xxxxx" or 'xxxxx'
- use for including quotes in strings, e.g: 'The word "no" is small.'
- multiline: delimit with triple quotes: ''' or """
-
Subtopic
- example
- \"
- backslash must be escaped with a backslash
- \\
-
concatenation
-
use + operator
- example
- Subtopic
-
splitting
- Subtopic
-
repetition
-
use the * operator
- example
- Subtopic
-
formatting
-
characters available
- example
- 'Her name is %s.' % her_name
- see documentation for list: http://www.python.org/doc/current/lib/typesseq-strings.html
- can even use dictionaries
- 'The value is %(key)s' % my_dictionary
-
flags available
- see: http://www.python.org/doc/current/lib/typesseq-strings.html
-
can be treated as an array
- my_string[5]
-
can be iterated over
- for each_character in my_string:
-
get length
- Subtopic
-
containers
- act like Vectors, in that you can mix datatypes
-
sequences
-
lists
- one-dimensional dynamic arrays
- mutable: add and delete items after creation
- Elements can be complex data types.
- defined with brackets
- Subtopic
- zero-based indicies
- negative numbers can be used to indicate elements from end of array, with -1 being the last element
- slices, array ranges, via [x:y]
- non-inclusive for second parameter: array[:2] does not include my_array(2)
- omit first or last value in range to start from beginning/end
- appending
- Subtopic
- example
- Subtopic
- Subtopic
- example
- Subtopic
- Subtopic
- example
- Subtopic
-
tuples
- act like lists
- immutable
- once created, the elements cannot be changed
-
dictionaries
- associative arrays
- hash tables
-
declaring
- curly parenthesis
- Subtopic
- Subtopic
- The value can be a complex data structure.
- dict()
- dict can be subclassed
-
accessing values
- Subtopic
-
can use function labels
- Subtopic
-
iteration
- over keys
- Subtopic
- over values
- Subtopic
- add pairs dynamically
-
test for existence of keys
- returns true if key exists
- Subtopic
- if 'key_in_question' in my_dictionary
-
sets
- built-in for version 2.5 and later
-
casting
-
int(<string>)
- convert a string to an integer
-
str(<integer>)
- convert an integer to a string
-
flow control
-
conditional execution
-
truth testing
-
true
- non-zero number or non-empty object
-
false
- zero or empty object
- comparison and equality tests return 0 or 1
-
Subtopic
-
example
- Subtopic
- Subtopic
-
repetition
-
Subtopic
-
interates through the elements in a collection
- example
- Subtopic
- use range() for a counting loop
- Subtopic
- Subtopic
-
Subtopic
- Subtopic
-
jump to next iteration
-
Subtopic
- Subtopic
-
break out of a loop
-
Subtopic
- Subtopic
-
do nothing, statement placeholder
- Subtopic
-
functions
-
Subtopic
-
creates a function object
-
assignment is allowed
- Subtopic
- so, don't call a function without parenthesis
-
support for optional arguments
- must come after mandatory arguments
-
form of optional (default) arguments
- x=<default value>
-
example
- def function_with_optional( required_parameter, optional_parameter=2 )
-
argument lists
- Subtopic
-
keyword argument lists
-
Subtopic
- the keyword argument list is a dictionary
-
Subtopic
- but immutable types are discarded and reassigned
- call with parenthesis notation
-
supports lambda functions
-
example
-
Subtopic
- creates an anonymouns function with the name of "anonymous_function"
-
returning values
- Subtopic
-
can return a tuple
- multiple values are returned with tuple unpacking
-
documentation
- can begin with a string defining the function
-
getting help on methods
-
in IPython, you can append a "?" to a method name to get more information
- example
- Subtopic
- output
- Subtopic
- Docstring is the documentation inside the program's code.
-
classes & objects
- Subtopic
-
scope
-
private
-
example
- Subtopic
-
"protected"
-
example
- _my_protected_variable
- just a convention, the member is accessible from outside the class
-
methods
- Subtopic
-
Subtopic
- Subtopic
- Subtopic
- Subtopic
-
constructors
-
Subtopic
- Subtopic
-
built-in overloadable methods
-
__call__(self, n)
- allows objects to be treated like function calls
- example
- Subtopic
-
__del__(self)
- overload default destructor
-
__len__(self)
- Subtopic
- example
- Subtopic
-
__cmp__(self, n)
- comparison
-
static
- Subtopic
- Subtopic
-
example
- Subtopic
- Method can reference class variables by explicitly naming the class.
- Can be called with an instance or just the class.
-
class
- Subtopic
-
A reference to the class must be the first parameter in the method's definition.
- Subtopic
- Subtopic
-
example
- Subtopic
- Subtopic
-
subclassing
- limited multiple inheritance
-
form
-
single inheritance
- Subtopic
-
multiple inheritance
- Subtopic
-
Subtopic
-
Subtopic
- bound method
-
call parent's methods by explicitly calling the super class
-
Subtopic
- Subtopic
-
"new-style" classes
- Subtopic
-
variables
-
Variables defined in a class are class variables.
-
example
- Subtopic
- Instances can override these class variables, creating local copies, but leaving the class variable unaffected.
- Subtopic
-
properties
-
requires that the class be a "new-style" class
- Topic
-
Instance variables accessible through getter and setter functions
- when calling code gets the property, the getter method is called
- when calling code sets the property, the setter method is called
-
Subtopic
- Subtopic
- example
- Subtopic
- delete()
- documentation attribute
-
A string after the class declaration is documentation for the class
-
example
- Subtopic
- Subtopic
-
objects
-
instantiation
-
call the class
- example
- Subtopic
-
comparing objects
-
Subtopic
- true if the objects are equal in value
-
Subtopic
- true if they point to the same object
-
Subtopic
- if a class variable of the same name exists, the appendage will override the class variable
-
Exceptions
-
format
- Subtopic
-
catching
-
Subtopic
- except IOError:
-
Subtopic
- except:
- except takes an optional object parameter
- To figure out what exception needs to be handled, run the offending code. When Python breaks, the error message will tell you the exception thrown.
-
To catch multiple exceptions with one block of code, use a tuple.
- Subtopic
-
raising
- Subtopic
- Subtopic
-
documentation
- can begin with a string defining the class
-
getting help on objects
- Subtopic
-
Subtopic
- gives the names inside an object
- can be used on packages
- reflection
-
dir()
- names of objects in current scope
-
locals()
- Returns a dictionary of the current scope. Names are the keys, definitions are the values.
- Subtopic
-
Subtopic
- get Python's internal identity for an object
- all objects have a unique number
-
built-in fuctions
-
Subtopic
- length of a list
-
Subtopic
-
appends newline
-
examples
- Subtopic
-
getting user input
-
Subtopic
- get input from your user via a prompt
- raw_input(<optional prompt string>)
-
converting data
- Subtopic
-
Subtopic
- get a string representation
- Subtopic
- Subtopic
- Subtopic
- Subtopic
-
Subtopic
- get the ASCII code of a character
-
Subtopic
- string to float
-
Subtopic
- string to integer
-
extremes
- Subtopic
- Subtopic
-
string manipulation
- Subtopic
-
Subtopic
- first character of string
- Subtopic
- Subtopic
- Subtopic
- Subtopic
-
Subtopic
- trailing/leading whitespace
-
create an iterator for a collection
- Subtopic
-
Subtopic
- Subtopic
-
command-line applications
-
list of calling parameters
-
sys.argv
-
example
- Subtopic
-
parse into tuple
- getopt.getopt(sys.argv, <string of short, single letter, options>, <list of long options>)
-
signal handling
-
uses "signal" library
-
to trap and handle a signal
- signal.signal(signal.<SIG constant>, <label_of_method you want to call>)
- example of handling CTL-C
- Subtopic
-
Subtopic
- signal.signal(signal.<SIG constant>, signal.SIG_IGN)
-
Linux signals
-
Subtopic
- generate #14, SIGALRM
- signal.alarm(<number of seconds to wait before generating alarm>)
-
make script files executable
-
Linux
- add #!/usr/bin/env python to top of file
- if __name__ == '__main__':
-
debugging & performance
- profiling
-
logging
-
system
-
use 'syslog' module
- syslog( string )
-
assert <test>[, string]
- use to force a traceback if the test fails
-
example
- Subtopic
- does not evaluate if Python is run with -O or -OO
-
libraries/modules
-
importing
-
import entire library
-
format
- Subtopic
-
import function from a library
-
format
- Subtopic
-
import library with an alias
-
import a_module as another_name_for_module
- Subtopic
-
importing forces Python to evaluate the imported code
- but only the first time it is imported into a program
- "imp" module
- Subtopic
-
specific functionality
-
regular expressions
- "re"
-
plotting
- "Gnuplot"
-
operating system functionality
-
"os"
- getcwd()
- get current working directory
- listdir()
- list directory contents
- chown()
- chmod()
- rename()
- remove()
- mkdir()
- system()
- execute command
- environment variables
- os.environ
- dictionary
-
numerical
- "NumPy"
-
profiling
- "profile"
- create namespaces
-
documenting
- can begin with a string describing the module
-
make runnable, only if called from command line
-
Subtopic
- Subtopic
- block will not run when imported
-
packages
- collections of modules
-
organized in directories
-
Subtopic
- code in this file evaluated first time a module from the package is imported
-
importing
- Subtopic
-
Subtopic
-
example
- import my_package.my_module
-
Within a package, modules can import from the same packagewithout giving the path.
- assumes current path of module
-
packages can be zipped
- use PyZipFile
- Subtopic
-
repository for Python packages
- http://pypi.python.org/pypi
- bound/unbound
-
scoping
-
globals
-
if you must use globals, be sure to declare them in your functions, or assignment will produce local variables
-
syntax
- Subtopic
-
I/O
-
files
-
simple
-
opening
- Subtopic
-
reading
- file_contents = file_handle.read()
- as a collection of lines
- file_handle.readlines()
- example
- Subtopic
- Subtopic
- Subtopic
-
closing
- file_handle.close()
-
sys.open()
- read( number_of_bytes_or_blank_for_entire_file )
- readline()
- readlines()
- write( string_to_write )
- writelines( list_of_strings_to_write )
- close()
-
temporary
-
use "tempfile" module
- mktemp()
- Subtopic
-
a file in Python is an iterator over the lines of the file
- Subtopic
-
pipes
-
stdin
-
sys.stdin
- read()
- readline()
- readlines()
-
stdout
-
sys.stdout
- write()
- Subtopic
- flush()
- Subtopic
- os.popen( command_as_string, r_or_w )
-
exceptions
- IOError
-
GUI development
-
Tk
-
Tkinter
-
Pmw
- http://pmw.sourceforge.net/
-
wxPython
- http://wxpython.org
- iterator protocol
-
iterators
-
definition
-
an object implementing the iterator protocol
-
iterator protocol requires implementation of two methods:
- next
- returns each item iterated over
- Subtopic
- __iter__
- returns the iterator
-
Subtopic
- Subtopic
- no built-in way to rewind an iterator
- The developer of the class must add rewind functionality.
-
example
- Subtopic
- Subtopic
- Subtopic
- you could add a method to rewind the class, or alter the sequence of delivery in any way
- Subtopic
-
generating functions
- return iterators
- Subtopic
-
simple example
-
Subtopic
- Subtopic
- could also use a for loop to iterate over my_iterator
- Subtopic
-
generator expression
- a shorthand for producing iterators
-
example
- Subtopic
- list displays