Python Cookbook

Overview

What is Python?

Python is a high-level, structured, open-source programming language that you can use for a wide variety of programming tasks. It was created by Guido Van Rossum back in the early 1990s. Interest in Python has increased tremendously in just the last five years. Python is named after “Monty Python’s Flying Circus.

Cross-platform Compatibility

There is a Python Interpreter for just about every platform (Unix, Windows, OS X, etc.). This means your Python code will run practically everywhere.

There are currently three major implementations

  • CPython, the Standard Implementation, written in C.
  • Jython, written in Java.
  • IronPython, written in C# for the .NET environment.

My Python Tutorial

Overview

I’m a technical writer, and as such, I’m continually documenting new things.

I’ve found that when I study a new subject, the best way for me to comprehend new concepts is by documenting my understanding as “the story evolves”.

To become competent with any new technology, you have to have a solid understanding of its fundamental concepts.

I’ve found that as I learn more and more about a subject, and am continually making new connections, I usually reach a point where I realize that I’ve misunderstood some basic concept. Sometimes I’m “blinded” by an assumption I’ve make, and sometimes I bark up the wrong tree because of the imprecision of my study material.

I do this because I’ve noticed that as my research progresses, my understanding evolves.

And I find that I have to continually revisit concepts that I learned earlier, and revise them.

When I learn new information, I like to make notes about about it.

I wrote this tutorial as a way to help me learn Python.

The process of writing this tutorial

while working my way through learing Python The material in My Pythohn Tutorial is based on the Official Python Tutorial, written by Guido Van Rossum (the guy who originally designed Python).

A Little About Python

Python was created as an alternative

An alternative to:

  • Shell Scripting.

    • And to overcome Shell Scripting’s limitations.

      • Python allows you to do more things than DOS.
  • ‘C’ Programming.

    • And to overcome ‘C’ programming’s limitation.

      • Namely, lines and lines of code to accomplish common tasks.

Python brings the power of ‘C’ to scripting

But unlike ‘C’, Python is an interpreted language.

  • There is no time-consuming compilation and linking.

  • Python affords Rapid Development.

    • It doesn’t require the usual write/compile/test/recompile cycle.

Python goes beyond shell scripting and ‘C’ programming

By offering support for:

  • Writing large structured programs.
  • More complex and robust error checking than C.
  • A host of built-in high-level data types.
  • Data structure handling (arrays, dictionaries, etc.).

Python allows you split your program into Modules

In Python, a Module is simply a source code file with a .py extension.

  • Modules can be used by other programs.

  • Python comes with a set of Standard Modules.

    • Which provide things like file I/O, System Calls, Sockets, and even interfaces to GUI toolkits (like Tk)

    • And upon which you can base your programs.

    • Or use as code examples to study to learn Python.

    • The following are among the most important:

      • time
      • sys
      • os
      • math
      • random
      • pickle
      • urllib
      • re
      • cgi
      • socket

The Python Interpreter is Interactive

You can invoke The Python Interpreter in an Interactive Shell (similar to a Windows Command Shell).

From inside it, you can run code instantly, at the “Interpreter Prompt”.

E.g.,

>>> print "Hello World!"
Hello World!

This is great for testing.

Python programming is different in that

  • The high-level data types allow you to express complex operations in a single statement.

  • Statement aren’t grouped using beginning and ending brackets, they’re grouped using indentation.

    • In Python:

      • Whitespace is significant.
      • You don’t declare variables or arguments.

Python is extensible

Python was designed to be used with compiled, executable, ‘C’ programs.

You can write functions (and modules) in ‘C’, and use them to add new ‘built-in’ functions or modules to the Python interpreter.

Yoy can do this to:

  • Run critical operations at maximum speed.
  • To link Python programs to ‘C’ libraries that might only be available in binary form (such as a vendor-specific graphics library).
  • Once you’re “hooked” on Python, you can link the Python interpreter into an application written in C, and use it as an extension or command language for that application.

The Python Interpreter

Your Python Deployment

On Windows, the Python Interpreter is the executable: “C:\Python27\python.exe” (“/usr/local/bin/python” on Unix).

You assign it an environment variable, and you “Path it”, so you can invoke it anywhere.

Python Home Environment Variable
PYTHON_HOME=C:\Python27\

Invoking the Interpreter

There are three ways to invoke the Python Interpreter.

Interactively

The Interperter is invoked from the standard input connected to a tty device.

In this case, the Interpreter reads and executes commands interactively.

Open a Command Terminal, and then type:

“python”, followed by Enter.

  • The Command Prompt (C:\>) turns into the “Python Primary Prompt” (>>>).

    • Note: The “Python Secondary Prompt” appears when the Interpreter expects you to enter another line of input.

    • Type the EOF character (press Ctrl+z) to quit.

      • You can also type import sys followed by sys.exit().
E.g.,

Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved.

C:\Users\Chris>python Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32 Type “help”, “copyright”, “credits” or “license” for more information. >>>

Running a Script from a File

In this case,

The Python Interpreter reads & executes a Python script that is passed to it as:

  • A filename argument.
  • Or with a file Piped into the standard input. (Python < filename).
With the Command Option

“python -c string [arguments…]”

The Interpreter reads & executes a set of Python statements from a string (immediately after processing the argument), and then exits.

  • The string contains the Python script, and
  • The [arguments…] contains the arguments to want to pass into it.
  • Since the space character is used to delimit the string, you must enlcose the Python script (essentially a set of Python statements) within quotes.
  • The arguments are assigned to the positional parameters, starting with sys.argv[0].

Argument Passing

Within a session, the Python Interpreter “remembers” variables and function/class definitions.

The Interpreter stores a script’s name and the arguments passed to it in the system variable sys.argv.

  • sys.argv is simply a List of Strings.

  • sys.argv[0] is used for the name of the script, and sys.argv[1 …] is used for the arguments.

  • sys.argv’s length is always at least one.

    • When no script and no arguments are given (i.e., when you just execute “Python”), sys.argv[0] just holds an empty string (‘’).

Interactive Mode

When commands are read from a tty (standard input, the Python Prompt), the interpreter is said to be in interactive mode.

  • In this mode it prompts for the next command with the primary prompt, usually three greater-than signs (“>>> “).
  • For continuation lines it prompts with the secondary prompt, by default three dots (“… “). Note that a secondary prompt on a line by itself in an example means you must type a blank line; this is used to end a multi-line command.

The Interpreter and Its Environment

Error Handling

When an error occurs, the interpreter prints an error message and a stack trace.

  • In interactive mode, the interpreter then returns to the primary prompt.
  • When input came from a file, the interpreter exits with a nonzero exit status after printing the stack trace.

Exceptions handled by an except clause in a try statement are not errors in this context.

Some errors are unconditionally fatal, and cause an exit with a nonzero exit.

  • This applies to internal inconsistencies, and some cases of running out of memory.

Error messages are written to the standard error stream. Nnormal output from the executed commands is written to Standard Output.

Typing the Interrupt character (usually Control-C or DEL) at the Primary or Secondary prompt, cancels the input, and returns to the Primary prompt.

  • Typing an Interrupt while a command is executing, raises the KeyboardInterrupt exception, which can be handled by a try statement.

Executable Python Scripts

On BSD’ish Unix systems, Python scripts can be made directly executable (like shell scripts) by putting the line:

“#! /usr/bin/env python” at the beginning of the script and giving the file an executable mode.

The “#!” must be the first two characters of the file.

  • I don’t know if this works in Windows.

The Interactive Startup File

When you use Python interactively, you can configure the Interpreter Environment with a set of standard commands that execute every time you invoke the Interpreter.

$PYTHONSTARTUP

You can do this by setting an environment variable named $PYTHONSTARTUP to the name of a file containing your start-up commands.

  • This file is known as the Global Start-up File.
  • The Interpreter maintains a handle to this file in the system variable os.environ[‘PYTHONSTARTUP’].

The Global Start-up File is read in interactive sessions only. I.e.,

  • Not when Python reads commands from a script.

  • Not when “/dev/tty” is given as the explicit source of commands (which otherwise behaves like an interactive session).

    • I’m not familiar with this terminology.

The Global Start-up File is executed in the same Namespace in which interactive commands are executed.

  • This means that the objects defined in the Global Start-up File, and the object it imports, can be used without qualification in the interactive session.
Altering the Look of the Primary and Secondary Prompts

You can reconfigure the prompts sys.ps1 and sys.ps2 in the Global Start-up File.

Bootstrapping Additonal Script Files

You can use the Global Start-up File as a Master Include File, to read additional start-up scripts from the current directory.

E.g.

By including the line: “execfile(‘.pythonrc’)”.

Calling the Global Start-up file from a Python Script

You can go the other direction, you can call the Global Start-up file explicitly in the script.

E.g.,

import os if os.path.isfile(os.environ[‘PYTHONSTARTUP’]): execfile(os.environ[‘PYTHONSTARTUP’])

An Informal Introduction to Python

Using Python Interactively

You type in an expression, and the answer appears on the next line (and the current Primary Prompt appears on the line after it).

  • When you type “_” at the Primary Prompt, the Interpreter outputs the exact same thing it did the last time.
Numbers

In interactive mode, the last printed expression is assigned to the variable “_”.

Strings
Escaping

You can type multiple lines and yet have them input as a single line, by ending the each line with the escape character (\) - which continues a line.

You can type a single line and have them interpreted as multiple individual lines input separately, by typing the newline character (\n) to mark the end of each line.

Triple Quotes

You can surround a whole block of text with triple quotes (“”“bla bla bla”“”).

Concatonation

You can concatenate Strings by typing the + operator.

>>> word = 'Help' + 'A'
>>> word
'HelpA'

You can repeat Strings by typing the * operator.

>>> '<' + word*5 + '>'
'<HelpAHelpAHelpAHelpAHelpA/>'

Two string literals next to each other are automatically concatenated.

>>> word = 'Help' 'A'
Strings can be subscripted (indexed), like in C

An Index value:

  • Identifies a particular character in a String.
  • Specifying its character position.
  • I.e., the number of characters from the beginning of the String.

The first character of a string has subscript (index) 0.

In Python, there is no separate character type (like char, in ‘C’). In Python, a character is simply a string of size one.

Substrings can be specified using two indices separated by a colon. This is known as slice notation.

  • The first index specifies where the substring begins.
  • The second index specifieds where the substring ends (non-inclusively).
>>> word
'HelpA'
>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

Slice indices have useful defaults.

An omitted first index defaults to zero.

An omitted second index defaults to the size of the String.

>>> word[:2]    # The first two characters
'He'
>>> word[2:]    # All but the first two characters
'lpA'

Here’s a useful invariant of slice operations: s[:i] + s[i:] equals s.

>>> word[:2] + word[2:]
'HelpA'
>>> word[:3] + word[3:]
'HelpA'

Degenerate slice indices are handled gracefully:

  • An index that is too large, is replaced by the string size.
  • An upper bound with a value that is less than the lower bound, always returns an empty string.
>>> word[1:100]
'elpA'
>>> word[10:]
''
>>> word[2:1]
''

You can use negative Indices to count backwards from the end of the String:

>>> word[-1]     # The last character
'A'
>>> word[-2]     # The last-but-one character
'p'
>>> word[-2:]    # The last two characters
'pA'
>>> word[:-2]    # All but the last two characters
'Hel'

Out-of-range negative slice indices are truncated, but don’t try this for single-element (non-slice) indices:

>>> word[-100:]
'HelpA'
>>> word[-10]    # error
Traceback (innermost last):
  File "<stdin/>", line 1
IndexError: string index out of range

The best way to remember how slices work is to think of the indices as pointing between characters, with the left edge of the first character numbered 0. Then the right edge of the last character of a string of n characters has index n, for example:

H e l p A

0 1 2 3 4 5

-5
-4
-3
-2 -1
  • The first row of numbers gives the position of the indices 0…5 in the string.
  • The second row gives the corresponding negative indices.

The slice from i to j consists of all characters between the edges labeled i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds, e.g., the length of word[1:3] is 2.

The Length of a String

You can find the length of a String using the built-in function len().

>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
Lists

Python knows a number of compound data types that are used to group together other values. The most versatile is the ist.

A List is written as a String of comma-separated values (items) - between brackets ([]).

List items need not all have the same type.

>>> a = ['spam', 'eggs', 100, 1234]
>>> a
['spam', 'eggs', 100, 1234]
List Items are Indexed

Like String Indices, List Indices start at 0, and lists can be sliced, concatenated and so on.

>>> a = ['spam', 'eggs', 100, 1234]
>>> a[0]
'spam'
>>> a[3]
1234
>>> a[-2]
100
>>> a[1:-1]
['eggs', 100]
>>> a[:2] + ['bacon', 2*2]
['spam', 'eggs', 'bacon', 4]
>>> 3*a[:3] + ['Boe!']
['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Arrays Contain Variable Contents

Unlike Strings, which are immutable, you can manipulate the contents of List elements.

>>> a
['spam', 'eggs', 100, 1234]
>>> a[2] = a[2] + 23                            # Re-assignment.
>>> a
['spam', 'eggs', 123, 1234]
Assignment to slices is also possible

You can even change the size of the List.

>>> # Replace some items:
... a[0:2] = [1, 12]
>>> a
[1, 12, 123, 1234]
>>> # Remove some:
... a[0:2] = []
>>> a
[123, 1234]
>>> # Insert some:
... a[1:1] = ['bletch', 'xyzzy']
>>> a
[123, 'bletch', 'xyzzy', 1234]
>>> a[:0] = a     # This insert a copy of itself at the beginning of the List.
>>> a
[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
The Length of a List

You can get the number of Items in the List with the function len().

>>> len(a)
8
Nesting Lists

You can create Lists containing other Lists.

>>> q = [2, 3]
>>> p = [1, q, 4]
>>> len(p)
3
>>> p[1]
[2, 3]
>>> p[1][0]               # Give me the zeroith item from the list resulting from p[1] ( which is [2, 3]).
2
>>> p[1].append('xtra')   # See section 5.1
>>> p
[1, [2, 3, 'xtra'], 4]
>>> q                     # Note that p[1] and q point to the same object.
[2, 3, 'xtra']

First Steps Towards Programming

You can use Python for accomplishing tasks taht are more complicated than adding two and two.

For instance, you can write a Python script to claculate the initial subsequence of the Fibonacci series.

>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while b < 10:
...       print b
...       a, b = b, a+b
...
1
1
2
3
5
8
Multiple Assignment in a Single Statement

The first line contains a multiple assignment.

The variables a and b simultaneously get the new values 0 and 1 (respectively).

Multiple Assignment is used again in the last line.

  • The expressions are evaluated before the assignment.
Loop While True

The while loop iteratively executes as long as the condition (here: b < 10) holds true.

As in C, in Python:

  • Positive integers evaluate to boolean True.
  • Zero and negative integers evaluate to boolean False.

You can create an infinite loop condition with the statement:

while True:

You can also use:

while 1: # Because the number one always tests True.
The condition can also be any sequence

That means Strings and Lists.

  • As long as it has a non-zero length.
  • Empty sequences are always False.

The standard comparison operators are written the same as in C:

  • <
  • >
  • ==
  • <=
  • >=
  • !=
Indentation is Python’s way of grouping statements

The body of the loop is indented.

Python does not (yet!) provide an intelligent input line editing facility, so you have to type a tab or space(s) for each indented line.

In practice, you’ll prepare more complicated input for Python with a text editor such as EditPad Pro 7, which automatically indents for you.

When you enter a compound statement interactively, you must enter a blank line to comple the statement. This is because the parser can’t predict when you have typed the last line.

The print statement writes the value of the expression(s) it is given

It differs from just writing the expression you want to write (as we did earlier in the calculator examples) in the way it handles multiple expressions and strings.

Strings are printed without quotes, and a space is inserted between items

so you can format things nicely, like this:

>>> i = 256*256
>>> print 'The value of i is', i
The value of i is 65536
A trailing comma avoids the newline after the output
>>> a, b = 0, 1
>>> while b < 1000:
...     print b,
...     a, b = b, a+b
...
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Note that the interpreter inserts a newline before it prints the next prompt if the last line was not completed.

More Control Flow Tools

if Statements

Perhaps the most well-known statement type is the if statement. For example:

>>> if x < 0:
...      x = 0
...      print 'Negative changed to zero'
... elif x == 0:
...      print 'Zero'
... elif x == 1:
...      print 'Single'
... else:
...      print 'More'
...

There can be:

  • zero or more elif parts,
  • and the else part is optional.

The keyword elif is short for else if, and is useful to avoid excessive indentation.

An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.

for Statements

The for statement in Python differs slightly from what you might be used to in C or Pascal.

Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or leaving the user completely free in the iteration test and step (as C),

Python’s for statement iterates over the items of any sequence (e.g., a list or a string), in the order that they appear in the sequence.

For example (no pun intended):

>>> # Measure some strings:
... a = ['cat', 'window', 'defenestrate']
>>> for x in a:
...     print x, len(x)
...
cat 3
window 6
defenestrate 12
Modifying as you Iterate

It is not safe to modify the sequence being iterated over in the loop (this can only happen for mutable sequence types, i.e., lists).

If you need to modify the list you are iterating over, e.g., duplicate selected items, you must iterate over a copy and the slice notation makes this particularly convenient:

for x in a[:]: # make a slice copy of the entire list
if len(x) > 6: a.insert(0, x)

a [‘defenestrate’, ‘cat’, ‘window’, ‘defenestrate’]

The range() Function

range() is for iterating over a sequence of numbers.

range() automatically generates a list - containing an arithmetic progression
>>> range(10)            # Give me a list of 10 integers, in a sequence, beginning with the number zero.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The given end point is never part of the generated list

range(10) generates a list of 10 values, exactly the legal indices for items of a sequence of length 10.

It is possible to let the range start at another number

or to specify a different increment (even negative):

>>> range(5, 10)            # Give me a list of (10 - 5 = 5) integers, in a sequence, beginning with the number five.
[5, 6, 7, 8, 9]
>>> range(0, 10, 3)
[0, 3, 6, 9]
>>> range(-10, -100, -30)
[-10, -40, -70]
To iterate over the indices of a sequence

Combine range() and len() as follows:

a = [‘Mary’, ‘had’, ‘a’, ‘little’, ‘lamb’] # A list with five elements.

for i in range(len(a)):
print i, a[i]

0 Mary 1 had 2 a 3 little 4 lamb

break and continue Statements, and else Clauses on Loops

Just like in ‘C’, the “break” statement breaks-out of the most directly enclosing “for” or “while” loop.

And again, just like in ‘C’, the “continue” statement continues with the next iteration of the loop.

Loop statements can have an associated “else” clause

An associated “else” clause is executed when:

  • The loop terminates through exhaustion of the list (in the case of a “for” loop).
  • Or when the condition becomes false (in the case of a “while” loop).

But not when the loop is terminated by a break statement!

This is exemplified by the following loop, which searches for prime numbers:

for n in range(2, 10): # [2, 3, 4, 5, 6, 7, 8, 9].
for x in range(2, n):
if n % x == 0:
print n, ‘equals’, x, ‘*’, n break
else:
print n, ‘is a prime number’

2 is a prime number 3 is a prime number 4 equals 2 * 2 5 is a prime number 6 equals 2 * 3 7 is a prime number 8 equals 2 * 4 9 equals 3 * 3

The pass Statement

The pass statement does nothing.

It can be used when a statement is required syntactically, but the program requires no action.

For example
while 1:
pass # Busy-wait for keyboard interrupt

Defining Functions

The keyword “def”:

  • Introduces a function definition.
  • Must be followed by:
    • The function name, and
    • The parenthesized list of formal parameters.
E.g.,

We can create a function that writes the Fibonacci series to an arbitrary boundary:

def fib(n):    # write Fibonacci series up to n
   "Print a Fibonacci series up to n"
   a, b = 0, 1
   while b < n:
      print b,
      a, b = b, a+b

# Now call the function we just defined:
fib(2000)

1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597

The Function Body

The statements that form the body of the function start at the next line, indented by a tab stop.

The DocString

The first statement of the function body can optionally be a string literal; this string literal is the function’s documentation string, or docstring.

There are tools which use docstrings to automatically produce printed documentation, or to let the user interactively browse through code.

It’s good practice to include docstrings in code that you write, so try to make a habit of it.

A Function’s Variables

The execution of a function introduces a new Symbol Table called the Local Symbol Table. It is used for the storage of the values of the local variables declared in the function.

When you reference a variable in your Python program, the Python Interpreter searches for it by checking:

  • The local symbol table,
  • Then in the global symbol table, and
  • Then in the table of built-in names.

Thus, global variables cannot be directly assigned a value within a function (unless named in a global statement), although they can be referenced.

Passing Parameters to a Function

Parameters passed to a function are received as arguments, copies of which are stored in the function’s local symbol table.

Thus, arguments are passed using call by value.

When a function calls another function, a new local symbol table is created for that call.

A function definition introduces the function name in the current symbol table.

The Function Name

The value of the function name has a type that is recognized by the interpreter as a user-defined function.

Function Aliasing

This value can be assigned to another name which can then also be used as an alias for that function.

This serves as a general renaming mechanism.

E.g.,
>>> fib
<function object at 10042ed0/>
>>> f = fib
>>> f(100)
1 1 2 3 5 8 13 21 34 55 89
Function vs. Procedure

You might object that fib is not a function, but a procedure (because it doesn’t return a value (printing the values is just part of what it does)).

In Python (like in C), procedures are just functions that don’t return a value. In fact, technically speaking, procedures do return a value, albeit a rather boring one. This value is called None (it’s a built-in name).

Functions

Return a value.

Procedures

Dont return a value.

Writing the value None is normally suppressed by the interpreter if it would be the only value written

You can see it if you really want to:

>>> print fib(0)
None
Returning a List vs. Printing

You can write a function that returns a list of the numbers of the Fibonacci series, instead of printing it:

def fib2(n): # return Fibonacci series up to n
   "Return a list containing the Fibonacci series up to n"
   result = []
   a, b = 0, 1
   while b < n:
       result.append(b)    # see below
       a, b = b, a+b
   return result
>>> f100 = fib2(100)    # call it
>>> f100                # write the result
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
The return statement returns with a value from a function

You can make a function call, and assign the value it returns, to a variable, in a single statement.

Returning without an expression argument is used to return from the middle of a procedure.

Falling off the end also returns from a procedure, in which case the “None” value is returned.

Methods

The statement result.append(b) calls a method of the list object result.

Instance Calling

A method is a function that belongs to an object.

It is named obj.methodname, where:

  • obj is some object (this can be an expression), and
  • methodname is the name of a method that is defined by the object’s type (in it class definiton).
Different types define different methods

A class defines a type.

Methods of different types can have the same name without causing ambiguity.

It is possible to define your own object types and methods, using classes, as discussed later in this tutorial.

The method append() shown in the example, is defined for list objects

It adds a new element at the end of the list.

In this example, it is equivalent to “result = result + [b]”, but more efficient.

More on Defining Functions

Default Argument Values

The most useful form is to specify a default value for one or more arguments. This creates a function that can be called with fewer arguments than is contained in it’s signature. E.g.,

def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
   while 1:
      ok = raw_input(prompt)
      if ok in ('y', 'ye', 'yes'): return 1
      if ok in ('n', 'no', 'nop', 'nope'): return 0
      retries = retries - 1
      if retries < 0: raise IOError, 'refusenik user'
      print complaint
This function can be called either like this:

sk_ok(‘Do you really want to quit?’)

or like this:

ask_ok(‘OK to overwrite the file?’, 2).

The second parameter (2) is passed to “retries” as a new value for “retries”.

This parameter is passed as a Positional parameter.

Where are default values evaluated?

The default values are evaluated at the point of function definition in the defining scope, so that e.g.

i = 5 def f(arg = i): print arg i = 6 f()

will print 5.

Keyword Arguments

Functions can also be called using keyword arguments of the form “keyword = value”. The keyword being the parameter’s formal name.

When you use keyword arguments, you can pass parameters out of order - as long as you pass them along with the formal name of the argument.

When you pass a parameter based on its position, you can pass just the parameter value.

Take the following function for instance:
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
   print "-- This parrot wouldn't", action,
   print "if you put", voltage, "Volts through it."
   print "-- Lovely plumage, the", type
   print "-- It's", state, "!"

voltage - is a positional parameter.

state, action, and type - are named parameters.

This function could be called in any of the following ways:

parrot(1000) parrot(action = ‘VOOOOOM’, voltage = 1000000) parrot(‘a thousand’, state = ‘pushing up the daisies’) parrot(‘a million’, ‘bereft of life’, ‘jump’)

Vut the following calls would all be invalid:

parrot() # The required argument (voltage) is missing. parrot(voltage=5.0, ‘dead’) # non-keyword argument following keyword. This doesn’t make sense to me. I think voltage can be treated like a Keyword argument, and that ‘dead’ must be treated as a Keyword argument (i.e., state = ‘dead’. parrot(110, voltage=220) # duplicate value for argument parrot(actor=’John Cleese’) # unknown keyword

In general, an argument list must have:

Positional arguments (if there are any) followed by any keyword arguments (if there are any).

And keywords must be chosen from the formal parameter names.

It’s not important whether a formal parameter has a default value or not.

Formal Parameter of the Form \*\*name

This is part of a mechanism that allows you to pass a variable number of parameters.

When a final formal parameter of the form \*\*name is present:

  • It receives a dictionary containing all keyword arguments whose keyword doesn’t correspond to a formal parameter.

This can be combined with a formal parameter of the form \*name:

  • which receives a tuple containing the positional arguments beyond the formal parameter list.
  • name must occur before \*\*name.

For example, if we define a function like this:

def cheeseshop(kind, *arguments, **keywords):
   print "-- Do you have any", kind, '?'
   print "-- I'm sorry, we're all out of", kind
   for arg in arguments: print arg
   print '-'*40
   for kw in keywords.keys(): print kw, ':', keywords[kw]

It could be called like this:

cheeseshop('Limburger', "It's very runny, sir.",
   "It's really very, VERY runny, sir.",
   client='John Cleese',
   shopkeeper='Michael Palin',
   sketch='Cheese Shop Sketch')

and this is what wuld print:

/– Do you have any Limburger ? /– I’m sorry, we’re all out of Limburger It’s very runny, sir. It’s really very, VERY runny, sir. /—————————————- client : John Cleese shopkeeper : Michael Palin sketch : Cheese Shop Sketch

Arbitrary Argument Lists

A function can be called with an arbitrary number of arguments.

Here, the arguments are wrapped in a tuple.

You can use zero or more normal arguments before the variable arguments. E.g.,

def fprintf(file, format, *args):
   file.write(format % args)
Lambda Forms

By popular demand, a few features commonly found in functional programming languages and Lisp have been added to Python.

With the lambda keyword, small anonymous functions can be created.

Lambda forms can be used wherever function objects are required.

They are syntactically restricted to a single expression.

Semantically, they are just syntactic sugar for a normal function definition.

Here’s a function that returns the sum of its two arguments:

“lambda a, b: a+b”.

Like nested function definitions, lambda forms cannot reference variables from the containing scope, but this can be overcome through the judicious use of default argument values, e.g.

def make_incrementor(n):
return lambda x, incr=n: x+incr

This doesn’t make sense to me. It requires more thought…

Documentation Strings

There are emerging conventions about the content and formatting of documentation strings.

The first line in a function or class definition should always be a short, concise summary of the object’s purpose.

For brevity, it should not explicitly state the object’s name or type, since these are available by other means (except if the name happens to be a verb describing a function’s operation).

This line should begin with a capital letter and end with a period.

If there are more lines in the documentation string, the second line should be blank, visually separating the summary from the rest of the description.

The following lines should be one of more of paragraphs describing the objects calling conventions, its side effects, etc.

The Python parser does not strip indentation from multi-line string literals, so tools that process documentation have to strip indentation.

This is done using the following convention

The first non-blank line after the first line of the string determines the amount of indentation for the entire documentation string.

You can’t use the first line since it is generally adjacent to the string’s opening quotes, so its indentation is not apparent in the string literal.

Whitespace equivalent to this indentation is then stripped from the start of all lines of the string.

Lines that are indented less should not occur, but if they occur all their leading whitespace should be stripped.

Equivalence of whitespace should be tested after expansion of tabs (to 8 spaces, normally).

Data Structures

The list data type has some more methods. Here are all of them.

More on Lists

insert(i, x)

Insert an item (x) at a given position (i).

a.insert(0, x) inserts at the front of the list.

a.insert(len(a), x) is equivalent to a.append(x).

append(x)

Equivalent to a.insert(len(a), x).

index(x)

Returns the index of the first item whose value is x.

If there is no such item, it throws an error.

remove(x)

Removes the first item whose value is x.

If there is no such item, it throws an error.

sort()

Sorts the list items in-place.

reverse()

Reverses the elements in-place.

count(x)

Returns the number of times x appears in the list.

An example that uses all list methods:
>>> a = [66.6, 333, 333, 1, 1234.5]
>>> print a.count(333), a.count(66.6), a.count('x')
2 1 0
>>> a.insert(2, -1)
>>> a.append(333)
>>> a
[66.6, 333, -1, 333, 1, 1234.5, 333]
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.6, -1, 333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
[333, 1234.5, 1, 333, -1, 66.6]
>>> a.sort()
>>> a
[-1, 1, 66.6, 333, 333, 1234.5]
Functional Programming Tools

There are three built-in functions that are very useful when used with lists:

  • filter()
  • map()
  • reduce()
filter(function, sequence)

Returns a sequence (of the same type, if possible) consisting of those items from the sequence for which function(item) is true.

For example, to compute some primes:

def f(x): return x%2 != 0 and x%3 != 0

filter(f, range(2, 25)) [5, 7, 11, 13, 17, 19, 23]

map(function, sequence)

Calls function(item) for each item in the sequence, and returns a list consisting of each value cubed.

For example, to compute some cubes:

def cube(x): return x*x*x

map(cube, range(1, 11)) [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

More than one sequence can be passed.

In this case, the function must have as many arguments as there are sequences, and is called with the corresponding item from each sequence (or None if some sequence is shorter than another).

If None is passed for the function, a function returning its argument(s) is substituted.

Combining these two special cases, we see that “map(None, list1, list2)” is a convenient way of turning a pair of lists into a list of pairs.

For example:

seq = range(8) def square(x): return x*x

map(None, seq, map(square, seq)) [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]

reduce(function, sequence)

Returns a single value constructed by calling the binary function func on:

  • The first two items of the sequence, then
    • On the result and the next item,
      • and so on.

For example, to compute the sum of the numbers 1 through 10:

def add(x,y): return x+y

reduce(add, range(1, 11)) 55

If there’s only one item in the sequence, its value is returned.

If the sequence is empty, an exception is raised.

A third argument can be passed to indicate the starting value.

In this case, the starting value is returned for an empty sequence, and the function is first applied to the starting value and the first sequence item, and then to the result and the next item, and so on.

For example:

def sum(seq):
def add(x,y): return x+y return reduce(add, seq, 0)

sum(range(1, 11)) 55

sum([]) 0

The del statement

You can use del to remove an item from a list, given its index instead of its value.

del can also be used to remove slices from a list (which we did earlier by assignment of an empty list to the slice).

For example:

a [-1, 1, 66.6, 333, 333, 1234.5]

del a[0] a [1, 66.6, 333, 333, 1234.5]

del a[2:4] a [1, 66.6, 1234.5]

del can also be used to delete entire variables:

del a

Note: Referencing the name a hereafter is an error (at least until another value is assigned to it)

Tuples and Sequences

Sequences

Lists and Strings are two examples of sequence data types, and they have many common properties.

e.g.,

indexing and slicing operations.

Since Python is an evolving language, other sequence data types might be added.

Tuples

The Tuple is another standard sequence data type.

A tuple consists of a number of values separated by commas.

E.g.,

t = 12345, 54321, ‘hello!’ t[0] 12345

t (12345, 54321, ‘hello!’) # Tuples are output enclosed within parentheses.

# Tuples can be nested: u = t, (1, 2, 3, 4, 5)

u ((12345, 54321, ‘hello!’), (1, 2, 3, 4, 5))

As you see in output, tuples are alway enclosed in parentheses - so nested tuples are interpreted correctly

You can input Tuples either with or without surrounding parentheses.

But parentheses are necessary when the tuple is part of a larger expression.

Tuples have many uses.

E.g.,

  • (x, y) coordinate pairs.
  • Employee records from a database.

Just like strings, Tuples are immutable.

It’s impossible to assign to the individual items of a tuple (they’re immutable).

But you can simulate much of the same effect with slicing and concatenation.

A special problem is the construction of tuples containing 0 or 1 items, but the syntax has some extra quirks to accommodate these.

Empty tuples are constructed using an empty pair of parentheses.

A tuple with one item is constructed by following a value with a comma (it’s insufficient to enclose a single value in parentheses).

For example:

>>> empty = ()
>>> singleton = 'hello',    # <-- note trailing comma
>>> len(empty)
0
>>> len(singleton)
1
>>> singleton
('hello',)
tuple packing

E.g.,

t = 12345, 54321, ‘hello!’

The values 12345, 54321 and ‘hello!’ are said to be packed together in the tuple “t”.

The reverse operation is also possible.

Tuple Unpacking

This is called tuple unpacking.

E.g.,

>>> x, y, z = t

To unpack a tuple, the list of variables on the left must have the same number of elements as the length of the tuple.

Note that multiple assignment is really just a combination of tuple packing and tuple unpacking!

Occasionally, the corresponding operation on lists is useful:

list unpacking.

This is supported by enclosing the list of variables in square brackets:

>>> a = ['spam', 'eggs', 100, 1234]
>>> [a1, a2, a3, a4] = a

Dictionaries

A Dictionary in Python is similar to a Map Associative Container in ‘C’.

  • Dictionary elements are referenced by their key (and not by their absolute position in the container - as for Lists).

  • Key names are:

    • usually Strings or Numbers.
    • non-mutable.
  • Dictionary elements are indexed using their keys.

  • No two elements in the Dictionary can have equivalent keys.

  • Element order is not important.

Using Tuples as Keys

Tuples can be used as keys if they contain only strings, numbers, or tuples.

You cannot use lists as keys, because lists can be modified in-place using their append() method.

It is best to think of a dictionary as an unordered set of key/value pairs,

with the requirement that the keys are unique (within one dictionary).

A pair of braces creates an empty dictionary: {}.

You can add initial key/value pairs to a dictionary by placing a comma-separated list of key/value pairs within the braces

This is also how you output a dictionary.

The main Dictionary operations are:

Storing a value with a key.

Retrieving a value given its key.

You can use “del” to delete a key/value pair.

When you save a value using a key that already exists in the Dictionary, then the old key value is overwritten with the new value.

You’ll get an error if you try to reference a non-existent key.

The keys() method

Use the keys() method on an instance of a dictionary object to return a list containing all of the keys in the dictionary - in random order though.

If you want the keys in the list sorted

you can apply the sort() method to the list.

To check whether a single key is in a dictionary

you can use the Dictionary’s has_key() method.

Here is a small example using a dictionary:
>>> tel = {'jack': 4098, 'sape': 4139}
>>> tel['guido'] = 4127
>>> tel
{'sape': 4139, 'guido': 4127, 'jack': 4098}     # Inserted anywhere in Dictionary???
>>> tel['jack']
4098
>>> del tel['sape']
>>> tel['irv'] = 4127
>>> tel
{'guido': 4127, 'irv': 4127, 'jack': 4098}
>>> tel.keys()
['guido', 'irv', 'jack']
>>> tel.has_key('guido')
1

More on Conditions

The conditions used to govern while and if structures can contain more types operators than just comparisons.

To determine wheter a value exists in a Sequence

The comparison operators in and not in are use to determine wheter a value exists in a Sequence.

To determine whether two objects are the same object

The operators is and is not compare two objects to determine whether they are the same object.

  • This only matters for mutable objects like lists.

All comparison operators have equal priority, and it always lower than that of numerical operators.

Comparisons can be chained together:

E.g.,

a < b == c

This tests whether a is less than b, and moreover if b is equal to c.

Comparisons can be combined by the Boolean operators an`d and `or.

Negation

The outcome of any Boolean expression can be negated using the not operator.

Boolean operators have a lower prioriy than Comparison operator

Of the Boolean operators:

  • not has the highest priority.
  • or had the lowest priority.

So that A and not B or C is equivalent to (A and (not B)) or C.

Of course, you can always use parentheses to express any desired composition.

The Boolean operators and and or are so-called shortcut operators:

Their arguments are evaluated from left to right,

and evaluation stops as soon as the outcome is determined.

E.g.,

If A and C are true, but B is false, then A and B and C does not evaluate the expression C.

In general, the return value of a shortcut operator, when used as a general value and not as a Boolean, is the last evaluated argument.

Boolean Return Values

It is possible to assign the result of a comparison or other Boolean expression to a variable.

E.g.,

>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
>>> non_null = string1 or string2 or string3
>>> non_null
'Trondheim'

Note that in Python, unlike C, assignment cannot occur inside expressions (shoot!).

Comparing Sequences and Other Types

Sequence objects can be compared to other objects with the same sequence type.

The comparison uses lexicographical ordering:

First,the first two items are compared, and if they differ, this determines the outcome of the comparison.

If they’re equal, then the next two items are compared, and so on, until either sequence is exhausted.

If two items to be compared are themselves sequences of the same type, the lexicographical comparison is carried out recursively.

If all items of two sequences compare equal, then the sequences are considered equal.

If one sequence is an initial subsequence of the other, the shorted sequence is the smaller one. ???

Lexicographical ordering for strings uses the ASCII ordering for individual characters.

Some examples of comparisons between sequences with the same types:

(1, 2, 3) < (1, 2, 4) [1, 2, 3] < [1, 2, 4] ‘ABC’ < ‘C’ < ‘Pascal’ < ‘Python’ (1, 2, 3, 4) < (1, 2, 4) (1, 2) < (1, 2, -1) (1, 2, 3) = (1.0, 2.0, 3.0) (1, 2, (‘aa’, ‘ab’)) < (1, 2, (‘abc’, ‘a’), 4)

Note that comparing objects of different types is legal.

The outcome is deterministic but arbitrary:

The types are ordered by their names.

Thus, a list is always smaller than a string, a string is always smaller than a tuple, etc.

Mixed numeric types are compared according to their numeric value, so 0 equals 0.0, etc.

The rules for comparing objects of different types should not be relied upon; they may change in a future version of the language.

Modules

If you quit the Python interpreter, and then restart it, you’ll lose the funtion definitions and variables from the first session.

Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter, and then running it with that file as input.

This is the process of creating a script.

As your program gets longer, you might want to split it into several files for easier maintenance.

You might also want to use a function you’ve already written, without copying its definition into each program.

To support this, Python has a way to put definitions in a file, and then use them in a script or in an interactive instance of the interpreter.

Such a file is called a module.

You can import definitions from a module into other modules, or into the Main Module.

The Main Module is the collection of variables that you have access to in a script, executed at the top-level and in calculator mode.

A module is a file that contains Python definitions and statements.

The file name is the module name with the suffix “.py”.

The module’s name is a string.

Within the module, it is globally accessable in the variable “__name__”.

To demonstrate, use your favorite text editor to create a file called “fibo.py” in the current directory, and copy & paste following contents into it:

# Fibonacci numbers module

def fib(n):    # write Fibonacci series up to n
   a, b = 0, 1
   while b < n:
      print b,
      a, b = b, a+b
def fib2(n): # return Fibonacci series up to n
   result = []
   a, b = 0, 1
   while b < n:
      result.append(b)
      a, b = b, a+b
   return result

Now enter the Python interpreter and import this module with the following command:

>>> import fibo

This doesn’t enter the names of the functions defined in fibo directly in the current symbol table, it only enters the module name fibo there. Using the module name you can now access the functions:

>>> fibo.fib(1000)
1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

If you intend to use a function often you can assign it to a local name:

>>> fib = fibo.fib
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

More on Modules

Modules Can Contain
Executable Statements

These statements are intended to initialize the module, and they’re executed just once - the first time the module is imported somewhere.

Function definitions

Each module has its own private symbol table, used as the global symbol table by all functions defined within that module.

This mean you don’t have to worry about the variables in your module colliding with the User’s global variables.

On the other hand, if you know what you are doing, you can touch a module’s global variables with the same notation used to refer to its functions: modname.itemname.

Modules can import other modules.

It’s customary (but not required) to place import statements at the beginning of a module (or script, for that matter).

The imported module names are placed in the importing module’s Global Symbol Table.

There’s a variant of the import statement that imports names from a module directly into the importing module’s symbol table.

For example:

>>> from fibo import fib, fib2
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local symbol table (so in the example, fibo is not defined).

There is even a variant to import all names that a module defines:

>>> from fibo import *
>>> fib(500)
1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore (_).

The Module Search Path
Compiled Python files

Standard Modules

The dir() Function

Packages

Importing * From a Package
Intra-package References

Input and Output

Fancier Output Formatting

Reading and Writing Files

Methods of File Objects
The pickle Module

Errors and Exceptions

Syntax Errors

Exceptions

Handling Exceptions

Raising Exceptions

User-defined Exceptions

Defining Clean-up Actions

Classes

A Word About Terminology

Lacking universally accepted terminology to talk about classes, I will make occasional use of Smalltalk and C++ terms.

I would use Modula-3 terms, since its object-oriented semantics are closer to those of Python than C++, but I expect that few readers have heard of it.

I also have to warn you that there’s a terminological pitfall for object-oriented readers. The word object in Python does not necessarily mean a class instance. Like C++ and Modula-3, and unlike Smalltalk, not all types in Python are classes.

The basic built-in types like integers and lists are not classes. And even somewhat more exotic types like files aren’t either. However, all Python types share some common semantics that is best described by using the word object.

Objects have individuality, and multiple names (in multiple scopes) can be bound to the same object. This is known as aliasing in other languages. This is usually not appreciated on a first glance at Python, and can be safely ignored when dealing with immutable basic types (numbers, strings, tuples). However, aliasing has an (intended!) effect on the semantics of Python code involving mutable objects such as lists, dictionaries, and most types representing entities outside the program (files, windows, etc.). This is usually used to the benefit of the program, since aliases behave like pointers in some respects. For example, passing an object is cheap since only a pointer is passed by the implementation; and if a function modifies an object passed as an argument, the caller will see the change. This obviates the need for two different argument passing mechanisms as in Pascal.

Python Scopes and Name Spaces

A First Look at Classes

Class Definition Syntax
Class Objects
Instance Objects
Method Objects

Random Remarks

Inheritance

Multiple Inheritance

Private Variables

Odds and Ends
Exceptions Can Be Classes

What Now?

Interactive Input Editing and History Substitution

Line Editing

History Substitution

Key Bindings

Commentary

Python Programming

This content was taken from WikiBooks - Python Programming: http://en.wikibooks.org/wiki/Python_Programming.

How To

How to Install Python

There are two versions of Python: v2.7 and v3.5; and both of those come in two flavors: 32-bit and 64-bit. Install the 32-bit flavor of the v2.7 version.

Note

This procedure documents my “fresh installation” (after uninstalling the 64-bit version (which doesn’t work properly)).

  1. Get version Python version 2.7.1 by visiting: Download Python <http://python.org/download/>_.

    Authoring\../images/download_python.png

    Choose the option to Save the file download (it saves to %USERPROFILE%Downloads).

    ..Note::

    The 64-bit version causes problems with Easy Install, and also with Sphinx to build pdf docs (which then can’t compile C++ code).

  2. Run the installer (pyton-2.7.10.msi).

    The installer creates the directory C:Python27, and copies all of the bits there.

  3. Set the PYTHON_HOME environment Variable. Note that this must be a System Environment Variable, not a User Environment Variable.

    PYTHON_HOME=C:Python27

  4. Add to you PATH: ;%PYTHON_HOME%;%PYTHON_HOME%Scripts

    Reboot you computer so the new environment variables take affect.

Install Easy_Install

  1. Download the installer. Visit setuptools 18.4 : Python Package Index <https://pypi.python.org/pypi/setuptools>_. At the top of the landing page, under the heading Installation Instructions, in the first sentence, you’ll see the tern ex_setup.py. Right-click it and choose “Save target as…”.

Install MingW32

MingW32 contains a set of compilers, and Python uses one of them.

  1. Download the latest version of MingW32.

    Note: Save the installer program (mingw-get-setup.exe).

  2. Run the installer as Administrator.

    Accept the defaults.

  3. Configure the installation. Part way through the installation process, the Installation Manager appears. Select Basic Setup in the left pane, and then check mingw32-base and mingw32-gcc-g++ in the right pane.

    1. Click Installation > Apply Changes.

      The Schedule Pending Actions dialog appears.

    2. In the Schedule Pending Actions dialog, click Apply.

      The Download Package dialog appears, and your chosen packages and downloaded and installed. This process take several minutees to complete.

    Close the Installation Manager.

  4. Create an environment variable.

    MinGW_HOME = C:MinGW

  5. Path it.

    ;%MinGW_HOME%/bin

  6. Create a new file called pydistutils.cfg in your home directory (C:\Python27\Lib\distutils\). [build] compiler=mingw32

How to Install a Python Package

A Python Egg is a single-file importable distribution format for Python-related projects. “Eggs are to Pythons as Jars are to Java” Eggs actually are richer than jars; they hold interesting metadata such as licensing details, release dependencies, etc.

To use a package from the Python Package Index (pypi), either “pip install package” (which means you have to get pip), or download, unpack and python setup.py install it (that is, the egg).

You can either Browse all packages, or you can use the Search feature.

To get the latest version, for some reason, you have to be in the %USERPROFILE% directory.

Note: You run easy_install from the Windows Command Shell - not from the Python Command Shell!

  1. Open a Win32 command prompt.
  2. Change directory to .
  3. Run
easy_install <package_name>

E.g.,

easy_install Pygments

Install the 3rdParty Python SDK

  1. Open a Command Prompt, navigate to %USERPROFILE%, and then run
easy_install 3rdParty

This is what the console output looks like.

C:\\Users\\Chris>easy_install 3rdParty

Searching for 3rdParty
Reading http://pypi.python.org/simple/3rdParty/
Reading http://github.com/3rdParty/python_3rdParty
Best match: 3rdParty 1.0.4

Downloading http://pypi.python.org/packages/2.7/t/3rdParty/3rdParty-1.0.4-py2.7.

egg#md5=865957102030c121daf211dd94f46a31
Processing 3rdParty-1.0.4-py2.7.egg
Moving 3rdParty-1.0.4-py2.7.egg to c:\\python27\\lib\\site-packages
Adding 3rdParty 1.0.4 to easy-install.pth file

Installed c:\\python27\\lib\\site-packages\\3rdParty-1.0.4-py2.7.egg
Processing dependencies for 3rdParty
Searching for urllib3
Reading http://pypi.python.org/simple/urllib3/
Reading https://github.com/shazow/urllib3
Reading http://code.google.com/p/urllib3/
Reading http://urllib3.readthedocs.org/
Best match: urllib3 1.5
Downloading http://pypi.python.org/packages/source/u/urllib3/urllib3-1.5.tar.gz#
md5=3ee4b375a095bb6098f1ed75f8058e48
Processing urllib3-1.5.tar.gz
Running urllib3-1.5\\setup.py -q bdist_egg --dist-dir c:\\users\\chris\\appdata\\loca
l\\temp\\easy_install-msgmbn\\urllib3-1.5\\egg-dist-tmp-pliubi
zip_safe flag not set; analyzing archive contents...
dummyserver.server: module references __file__
Adding urllib3 1.5 to easy-install.pth file

Installed c:\\python27\\lib\\site-packages\\urllib3-1.5-py2.7.egg
Finished processing dependencies for 3rdParty

Install Sphinx

  1. Open a Command Prompt, navigate to %USERPROFILE%, and then run
easy_install -U sphinx

Install rst2pdf

  1. Open a Command Prompt, navigate to %USERPROFILE%, and then run
easy_install rst2pdf

This is what you’ll see in the command output:

C:\\Users\\Chris>easy_install rst2pdf

Searching for rst2pdf
Reading http://pypi.python.org/simple/rst2pdf/
Reading http://rst2pdf.googlecode.com
Reading http://code.google.com/p/rst2pdf/downloads/list
Best match: rst2pdf 0.92
Downloading http://rst2pdf.googlecode.com/files/rst2pdf-0.92.tar.gz

Processing rst2pdf-0.92.tar.gz
Running rst2pdf-0.92\\setup.py -q bdist_egg --dist-dir c:\\users\\chris\\appdata\\local\\temp\\easy_install-xloblj\\rst2pdf-0.92\\egg-dist-tmp-vf702a

zip_safe flag not set; analyzing archive contents...
rst2pdf.createpdf: module references __file__
rst2pdf.image: module references __file__
rst2pdf.pdfbuilder: module references __file__
rst2pdf.styles: module references __file__
rst2pdf.tests.autotest: module references __file__
rst2pdf.tests.execmgr: module references __file__

Adding rst2pdf 0.92 to easy-install.pth file

Installing rst2pdf-script.py script to C:\\Python27\\Scripts
Installing rst2pdf.exe script to C:\\Python27\\Scripts
Installing rst2pdf.exe.manifest script to C:\\Python27\\Scripts

Installed c:\\python27\\lib\\site-packages\\rst2pdf-0.92-py2.7.egg
Processing dependencies for rst2pdf
Searching for reportlab>=2.4
Reading http://pypi.python.org/simple/reportlab/
Reading http://www.reportlab.com/
Best match: reportlab 2.6
Downloading http://pypi.python.org/packages/2.7/r/reportlab/reportlab-2.6.win32-py2.7.exe#md5=4fdbb80bead7701c26f765f2a9c1ec19

Processing reportlab-2.6.win32-py2.7.exe

reportlab.rl_config: module references __file__
reportlab.__init__: module references __file__
reportlab.lib.fontfinder: module references __file__
reportlab.lib.testutils: module references __path__
reportlab.lib.utils: module references __file__
reportlab.lib.utils: module references __path__
reportlab.pdfgen.pdfimages: module references __file__
creating 'c:\\users\\chris\\appdata\\local\\temp\\easy_install-ipj7_5\\reportlab-2.6-py
2.7-win32.egg' and adding 'c:\\users\\chris\\appdata\\local\\temp\\easy_install-ipj7_5\\reportlab-2.6-py2.7-win32.egg.tmp' to it

creating c:\\python27\\lib\\site-packages\\reportlab-2.6-py2.7-win32.egg
Extracting reportlab-2.6-py2.7-win32.egg to c:\\python27\\lib\\site-packages
Adding reportlab 2.6 to easy-install.pth file

Installed c:\\python27\\lib\\site-packages\\reportlab-2.6-py2.7-win32.egg

Finished processing dependencies for rst2pdf

Install Pygments

  1. Open a Command Prompt, navigate to %USERPROFILE%, and then run
easy_install Pygments

Resources

Python Documentation

http://www.python.org/doc/

Tutor

An Online discussion for learning programming with Python.

Actively support and help new python programmers.

Are populated by the authors of many of the Python textbooks currently available on the market.

https://mail.python.org/mailman/listinfo/tutor

Concepts

MANIFEST.in

The Manifest template. This is a list of instructions that specify how to generate your manifest file, MANIFEST, which is the exact list of files to include in your source distribution. The sdist command processes this template and generates a manifest based on its instructions and what it finds in the filesystem.

Notes

  • When the script name is given as “-” (meaning standard input), sys.argv[0] is set to “-“.
  • In interactive mode, the last printed expression is assigned to the variable “_”. This variable should be treated as read-only by the user. Don’t explicitly assign a value to it. You would create an independent local variable with the same name masking the built-in variable with its magic behavior.