Python 2.7 quick reference2013-04-24 13:51:32MDTPython 2.7 quick reference2013-04-24 13:51:32MDTintroIntroduction: What is Python?python3Python 2.7 and Python 3.xstartingStarting Pythonstarting-windowsUsing Python in Windowsstarting-linuxUsing Python in Linuxline-syntaxLine syntaxnamesNames and keywordstypesBasic typesnumeric-typesNumeric typesint-typeType int: Integerslong-typeType long: Extended-precision
integersbool-typeType bool: Boolean truth valuesfloat-typeType float: Floating-point
numberscomplex-typeType complex: Imaginary numberssequence-typesSequence typessequence-commonOperations common to all the sequence typesstr-typeType str: Strings of 8-bit
charactersstr-constantsString constantswhitespaceDefinition of “whitespace”str-methodsMethods on str valuesnew-str-formatThe string .format() methodgeneral-format-formGeneral form of a format codeformat-nameThe name partformat-conversionThe conversion
partformat-specThe spec partformat-var-lengthFormatting a field of variable lengthold-str-formatThe older string format operatorunicode-typeType unicode: Strings of 32-bit
charactersutf-8The UTF-8 encodinglist-typeType list: Mutable sequenceslist-methodsMethods on listslist-comprehensionsList comprehensionstuple-typeType tuple: Immutable sequencesbytes-typeThe bytes typebytes-to-3xUsing the bytes type in 3.x
conversionbytearray-typeThe bytearray typeset-typesTypes set and frozenset:
Set typesset-immutable-operationsOperations on mutable and immutable setsset-mutable-operationsOperations on mutable setsdict-typeType dict: Dictionariesdict-methodsOperations on dictionariesdict-comprehensionsDictionary comprehensionsfile-typeType file: Input and output filesfile-methodsMethods on file objectsNone-typeNone: The special placeholder valueexpressionsOperators and expressionspredicatesWhat is a predicate?iterableWhat is an iterable?interfaceDuck typing, or: what is an interface?localeWhat is the locale?basic-functionsBasic functionsabs-functionabs(): Absolute valueall-functionall(): Are all the elements of an
iterable true?any-functionany(): Are any of the members of an
iterable true?bin-functionbin(): Convert to binarybool-functionbool(): Convert to Booleanbytearray-functionbytearray(): Create a byte arraychr-functionchr(): Get the character with a given
codecmp-functioncmp(): Compare two valuescomplex-functioncomplex(): Convert to complex typedict-functiondict(): Convert to a dictionarydivmod-functiondivmod(): Quotient and remainderenumerate-functionenumerate(): Step through indices and
values of an iterablefile-functionfile(): Open a filefilter-functionfilter(): Extract qualifying elements
from an iterablefloat-functionfloat(): Convert to float typeformat-functionformat(): Format a valuefrozenset-functionfrozenset(): Create a frozen sethex-functionhex(): Convert to base 16int-functionint(): Convert to int typeinput-functioninput(): Read an expression from the
useriter-functioniter(): Produce an iterator over a
sequencelen-functionlen(): Number of elementslist-functionlist(): Convert to a listlong-functionlong(): Convert to long typemap-functionmap(): Apply a function to each
element of an iterablemax-functionmax(): Largest element of an
iterablemin-functionmin(): Smallest element of an
iterablenext-functionnext(): Call an iteratoroct-functionoct(): Convert to base 8open-functionopen(): Open a fileord-functionord(): Find the numeric code for a
characterpow-functionpow(): Exponentiationrange-functionrange(): Generate an arithmetic
progression as a listraw_input-functionraw_input(): Prompt and read a string
from the userreduce-functionreduce(): Sequence reductionreversed-functionreversed(): Produce a reverse
iteratorround-functionround(): Round to the nearest
integral valueset-functionset(): Create an algebraic setsorted-functionsorted(): Sort a sequencestr-functionstr(): Convert to str
typesum-functionsum(): Total the elements of a
sequencetuple-functiontuple(): Convert to a tupletype-functiontype(): Return a value's typeunichr-functionunichr(): Convert a numeric code to a
Unicode characterunicode-functionunicode(): Convert to a Unicode
stringxrange-functionxrange(): Arithmetic progression
generatorzip-functionzip(): Combine multiple
sequencesadvanced-functionsAdvanced functionsbasestring-functionbasestring: The string base classcallable-functioncallable(): Is this thing
callable?classmethod-functionclassmethod(): Create a class
methoddelattr-functiondelattr(): Delete a named
attributedir-functiondir(): Display a namespace's nameseval-functioneval(): Evaluate an expression in source
formexecfile-functionexecfile(): Execute a Python source
filegetattr-functiongetattr(): Retrieve an attribute of a
given nameglobals-functionglobals(): Dictionary of global name
bindingshasattr-functionhasattr(): Does a value have an attribute
of a given name?id-functionid(): Unique identifierisinstance-functionisinstance(): Is a value an instance of
some class or type?issubclass-functionissubclass(): Is a class a subclass of
some other class?locals-functionlocals(): Dictionary of local name
bindingsproperty-functionproperty(): Create an access-controlled
attributereload-functionreload(): Reload a modulerepr-functionrepr(): Representationsetattr-functionsetattr(): Set an attributeslice-functionslice(): Create a slice instancestaticmethod-functionstaticmethod(): Create a static
methodsuper-functionsuper(): Superclassvars-functionvars(): Local variablessimple-statementsSimple statementsassignment-statementThe assignment statement: name = expressionassert-statementThe assert statement: Verify
preconditionsdel-statementThe del statement: Delete a name or part
of a valueexec-statementThe exec statement: Execute Python source
codeglobal-statementThe global statement: Declare access to a
global nameimport-statementThe import statement: Use a
modulepass-statementThe pass statement: Do nothingprint-statementThe print statement: Display output
valuesprint-as-functionThe print() functioncompound-statementsCompound statementsblocksPython's block structurebreak-statementThe break statement: Exit a for or while loopcontinue-statementThe continue statement: Jump to the next
cycle of a for or whilefor-statementThe for statement: Iteration over a
sequenceif-statementThe if statement: Conditional
executionraise-statementThe raise statement: Cause an
exceptionreturn-statementThe return statement: Exit a function or
methodtry-statementThe try statement: Anticipate
exceptionswith-statementThe with statement and context
managersyield-statementThe yield statement: Generate one result
from a generatordefdef(): Defining your own functionsfunction-localsA function's local namespaceiteratorsIterators: Values that can produce a sequence of
valuesgeneratorsGenerators: Functions that can produce a sequence of
valuesdecoratorsDecoratorsexceptionsExceptions: Error signaling and handlingexception-termsDefinitions of exception termsexception-lifecycleLife cycle of an exceptionexception-hierarchyBuilt-in exceptionsclassesClasses: Defining your own typesold-classes-introOld-style classesold-class-defDefining an old-style classold-constructorInstantiation of an old-style class: The
constructor, .__init__()old-attribute-refAttribute references in old-style classesold-method-callMethod calls in an old-style classold-delInstance deletion: the destructor, .__del__()new-classes-introLife cycle of a new-style classnew-new-method__new__(): New instance creationnew-attr-accessAttribute access control in new-style classesnew-propertyProperties in new-style classes: Fine-grained
attribute access controlnew-slotsConserving memory with __slots__special-methodsSpecial method namesrich-compare-methodsRich comparison methodsbinary-operator-methodsSpecial methods for binary operatorsunary-operator-methodsUnary operator special methodsbuiltin-function-methodsSpecial methods to emulate built-in functionscall-method__call__(): What to do when someone
calls an instancecmp-method__cmp__(): Generalized
comparisoncontains-method__contains__(): The “in” and “not in” operatorsdel-method__del__(): Destructordelattr-method__delattr__(): Delete an
attributedelitem-method__delitem__(): Delete one item of a
sequenceenter-method__enter__: Context manager
initializationexit-method__exit__: Context manager
cleanupformat-method__format__: Implement the format() functiongetattr-method__getattr__(): Handle a reference
to an unknown attributegetattribute-method__getattribute__(): Intercept all
attribute referencesgetitem-method__getitem__(): Get one item from a
sequence or mappingiter-method__iter__(): Create an iteratornonzero-method__nonzero__(): True/false
evaluationrepr-method__repr__(): String representationreversed-method__reversed__(): Implement the reversed() functionsetattr-method__setattr__(): Intercept all
attribute changessetitem-method__setitem__(): Assign a value to
one item of a sequencestatic-methodsStatic methodsclass-methodsClass methodspdbpdb: The Python interactive debuggerpdb-startupStarting up pdbpdb-exportsFunctions exported by pdbpdb-commandsCommands available in pdbcommon-modulesCommonly used modulesmath-modulemath: Common mathematical
operationsstring-modulestring: Utility functions for stringsrandom-modulerandom: Random number generationtime-moduletime: Clock and calendar functionsre-modulere: Regular expression
pattern-matchingregex-charsCharacters in regular expressionsregex-functionsFunctions in the re modulecompiled-reCompiled regular expression objectsmatch-objectMethods on a MatchObjectsys-modulesys: Universal system interfaceos-moduleos: The operating
system interfaceos-stat-modulestat: Interpretation of file
statusos.path-moduleos.path: File and directory interfaceargparseargparse: Processing command line
argumentsargparse-defsTypes of command line argumentsargparse-flowOverall flow of argument processingargparse-initThe ArgumentParser() constructorargparse-add_argumentThe ArgumentParser.add_argument()
methodargparse-parse_argsThe ArgumentParser.parse_args()
methodargparse-utilitiesOther useful ArgumentParser methods