The Short Version

This is a minimal introduction to Python, based on my web tutorial, “Instant Python.” It targets programmers who already know a language or two but who want to get up to speed with Python. For information on downloading and executing the Python interpreter, see Chapter 1 .

The Basics

To get a basic feel for the Python language, think of it as pseudocode, because that’s pretty close to the truth. Variables don’t have types, so you don’t need to declare them. They appear when you assign to them and disappear when you don’t use them anymore. Assignment is done with the = operator, like this:

x = 42

Note that equality is tested by the == operator . You can assign several variables at once, like this:

x,y,z = 1,2,3
first, second = second, first
a = b = 123

Blocks are indicated through indentation and only through indentation. (No begin / end or braces.) The following are some common control structures :

if x < 5 or  (x > 10 and x < 20):
    print("The value is OK.")


if x < 5 or  10 < x < 20:
    print("The value is OK.")


for i in [1, 2, 3, 4, 5]:
    print("This is iteration number", i)


x = 10
while x >= 0:
    print("x is still not negative.")
    x = x - 1

The first two examples are equivalent.

The index variable given in the for loop iterates through the elements of a list 1 (written with brackets, as in the example). To make an “ordinary” for loop (that is, a counting loop), use the built-in function range .

# Print out the values from 0 to 99, inclusive
for value in range(100):
    print(value)

The line beginning with # is a comment and is ignored by the interpreter.

Now you know enough (in theory) to implement any algorithm in Python. Let’s add some basicuser interaction . To get input from the user (from a text prompt), use the built-in function input .

x = float(input("Please enter a number:"))
print("The square of that number is", x * x)

The input function displays the (optional) prompt given and lets the user enter a string. In this case, we were expecting a number and so converted the input to a floating-point number using float .

So, you have control structures, input, and output covered—now you need some snazzy data structures. The most important ones are lists and dictionaries . Lists are written with brackets and can (naturally) be nested.

name = ["Cleese", "John"]
x = [[1, 2, 3], [y, z], [[[]]]]

One of the nice things about lists is that you can access their elements separately or in groups, through indexing and slicing . Indexing is done (as in many other languages) by writing the index in brackets after the list. (Note that the first element has index 0.)

print(name[1], name[0]) # Prints "John Cleese"
name[0] = "Smith"

Slicing is almost like indexing, except that you indicate both the start and stop index of the result, with a colon ( : ) separating them.

x = ["SPAM", "SPAM", "SPAM", "SPAM", "SPAM", "eggs", "and", "SPAM"]
print(x[5:7]) # Prints the list ["eggs", "and"]

Notice that the end is noninclusive. If one of the indices is dropped, it is assumed that you want everything in that direction. In other words, the slice x[:3] means “every element from the beginning of x up to element 3, noninclusive” (well, element 3 is actually the fourth element, because the counting starts at 0). The slice x[3:] would, on the other hand, mean “every element in x , starting at element 3 (inclusive) up to, and including, the last one.” For really interesting results, you can use negative numbers, too: x[-3] is the third element from the end of the list.

Now then, what about dictionaries? To put it simply, they are like lists, except that their contents aren’t ordered. How do you index them then? Well, every element has a key , or a name , which is used to look up the element, just as in a real dictionary. The following example demonstrates the syntax used to create dictionaries :

phone = {"Alice" : 23452532, "Boris" : 252336,
         "Clarice" : 2352525, "Doris" : 23624643  }


person = {'first name': "Robin", 'last name': "Hood",
          'occupation': "Scoundrel" }

Now, to get person ’s occupation, you use the expression person["occupation"] . If you wanted to change the person’s last name, you could write this:

person['last name'] = "of Locksley"

Simple, isn’t it? Like lists, dictionaries can hold other dictionaries, or lists, for that matter. And naturally, lists can hold dictionaries, too. That way, you can easily make some quite advanced data structures.

Functions

Our next step is abstraction . You want to give a name to a piece of code and call it with a couple of parameters. In other words, you want to define a function(also called a procedure ). That’s easy. Use the keyword def , as follows:

def square(x):
    return x * x


print(square(2)) # Prints out 4

The return statement is used to return a value from the function.

When you pass a parameter to a function, you bind the parameter to the value, thus creating a new reference. This means that you can modify the original value directly inside the function, but if you make the parameter name refer to something else (rebind it), that change won’t affect the original. This works just like in Java, for example. Let’s take a look at an example:

def change(x):
    x[1] = 4


y = [1, 2, 3]
change(y)
print(y) # Prints out [1,4,3]

As you can see, the original list is passed in, and if the function modifies it, these modifications carry over to the place where the function was called. Note the behavior in the following example, however, where the function body rebinds the parameter:

def nochange(x):
    x = 0


y = 1
nochange(y)
print(y) # Prints out 1

Why doesn’t y change now? Because you don’t change the value ! The value that is passed in is the number 1, and you can’t change a number in the same way that you change a list. The number 1 is (and will always be) the number 1. What the example does change is what the parameter x refers to , and this does not carry over to the calling environment.

Python has all kinds of nifty things such as named arguments and default arguments and can handle a variable number of arguments to a single function. For more information about this, see Chapter 6 .

If you know how to use functions in general, what I’ve told you so far is basically what you need to know about them in Python.

It might be useful to know, however, that functions are values in Python. So if you have a function such as square , you could do something like the following:

queeble = square
print(queeble(2)) # Prints out 4

To call a function without arguments, you must remember to write doit() and not doit . The latter, as shown, only returns the function itself, as a value. This goes for methods in objects, too. Methods are described in the next section.

Objects and Stuff . . .

I assume you know how object-oriented programming works. Otherwise, this section might not make much sense. No problem—start playing without the objects, or check out Chapter 7 .

In Python, you define classes with the (surprise!) class keyword, as follows:

class Basket:

    # Always remember the *self* argument
    def __ init__(self, contents=None):
        self.contents = contents or []


    def add(self, element):
        self.contents.append(element)


    def print_me(self):
        result = ""
        for element in self.contents:
            result = result + " " + repr(element)
        print("Contains:", result)

Several things are worth noting in this example.

  • Methods are called like this: object.method(arg1, arg2) .

  • Some arguments can be optional and given a default value (as mentioned in the previous section on functions). This is done by writing the definition like this:

    def spam(age=32): ...
  • Here, spam can be called with one or zero parameters. If it’s called without any parameters, age will have the default value of 32.

  • repr converts an object to its string representation. (So if element contains the number 1, then repr(element) is the same as "1" , whereas 'element' is a literal string.)

No methods or member variables (attributes) are protected (or private or the like) in Python. Encapsulation is pretty much a matter of programming style. (If you really need it, there are naming conventions that will allow some privacy, such as prefixing a name with a single or double underscore.)

Now, about that short-circuit logic . . .

All values in Python can be used as logic values. Some of the more empty ones (such as False , [] , 0 , "" , and None ) represent logical falsity; most other values (such as True , [0] , 1 , and "Hello, world" ) represent logical truth.

Logical expressions such as a and b are evaluated like this:

  • Check if a is true.

  • If it is not , then simply return it.

  • If it is , then simply return b (which will represent the truth value of the expression).

The corresponding logic for a or b is this:

  • If a is true, then return it.

  • If it isn’t, then return b .

This short-circuit mechanism enables you to use and and or like the Boolean operators they are supposed to implement, but it also enables you to write short and sweet little conditional expressions. For example, this statement:

if a:
    print(a)
else:
    print(b)

could instead be written like this:

print(a or b)

Actually, this is somewhat of a Python idiom, so you might as well get used to it.

Note

Python also has also actual conditional expressions , so you can write this:

print(a if a else b)

The Basket constructor ( Basket.__init__ ) in the previous example uses this strategy in handling default parameters. The argument contents has a default value of None (which is, among other things, false); therefore, to check if it had a value, you could write this:

if contents:
    self.contents = contents
else:
    self.contents = []

Instead, the constructor uses this simple statement:

                  self.contents = contents or []                                                                                            

Why don’t you give it the default value of [] in the first place? Because of the way Python works, this would give all the Basket instances the same empty list as default contents. As soon as one of them started to fill up, they all would contain the same elements, and the default would not be empty anymore. To learn more about this, see the discussion about the difference between identity and equality in Chapter 5 .

Note

When using None as a placeholder as done in the Basket.__init__ method, using contents is None as the condition is safer than simply checking the argument’s Boolean value. This will allow you to pass in a false value such as an empty list of your own (to which you could keep a reference outside the object).

If you would like to use an empty list as the default value, you can avoid the problem of sharing this among instances by doing the following:

def __init__(self, contents=[]):
    self.contents = contents[:]

Can you guess how this works? Instead of using the same empty list everywhere, you use the expression contents[:] to make a copy. (You simply slice the entire thing.)

So, to actually make a Basket and to use it (to call some methods on it), you would do something like this:

b = Basket(['apple', 'orange'])
b.add("lemon")
b.print_me()

This would print out the contents of the Basket : an apple, an orange, and a lemon.

There are magic methods other than __init__ . One such method is __str__ , which defines how the object wants to look if it is treated like a string. You could use this in the basket instead of print_me .

def __str__(self):
    result = ""
    for element in self.contents:
        result = result + " " + repr(element)
    return "Contains: " + result

Now, if you wanted to print the basket b , you could just use this:

print(b)

Cool, huh?

Subclassing works like this:

class SpamBasket(Basket):
    # ...

Python allows multiple inheritance, so you can have several superclasses in the parentheses, separated by commas. Classes are instantiated like this: x = Basket() . Constructors are, as I said, made by defining the special member function __init__ .

Let’s say that SpamBasket had a constructor __init__(self, type) . Then you could make a spam basket like this: y = SpamBasket("apples") .

If in the constructor of SpamBasket , you needed to call the constructor of one or more superclasses, you could call it like this: Basket.__init__(self) . Note that in addition to supplying the ordinary parameters, you must explicitly supply self , because the superclass __init__ doesn’t know which instance it is dealing with. A better (and slightly more magical) alternative would be super().__init__() .

For more about the wonders of object-oriented programming in Python, see Chapter 7 .

Some Loose Ends

Here, I’ll quickly review a few other useful things before ending this appendix. Most useful functions and classes are put in modules , which are really text files with the file name extension .py that contain Python code. You can import these and use them in your own programs. For example, to use the function sqrt from the standard module math , you can do either this:

import math
x = math.sqrt(y)

or this:

from math import sqrt
x = sqrt(y)

For more information on the standard library modules , see Chapter 10 .

All the code in the module/script is run when it is imported. If you want your program to be both an importable module and a runnable program, you might want to add something like this at the end of it.

if __name__ == "__main__": main()

This is a magic way of saying that if this module is run as an executable script (that is, it is not being imported into another script), then the function main should be called. Of course, you could do anything after the colon there.

And for those of you who want to make an executable script in UNIX, use the following first line to make it run by itself:

#!/usr/bin/env python

Finally, a brief mention of an important concept: exceptions. Some operations (such as dividing something by zero or reading from a nonexistent file) produce an error condition or exception . You can even make your own exceptions and raise them at the appropriate times.

If nothing is done about the exception, your program ends and prints out an error message. You can avoid this with a try / except statement, as in this example:

def safe_division(a, b):
    try:
        return a/b
    except ZeroDivisionError: pass

ZeroDivisionError is a standard exception. In this case, you could have checked if b was zero, but in many cases, that strategy is not feasible. And besides, if you removed the try / except statement in safe_division , thereby making it a risky function to call (called something like unsafe_division ), you could still do the following:

try:
    unsafe_division(a, b)
except ZeroDivisionError:
    print("Something was divided by zero in unsafe_division")

In cases in which you typically would not have a specific problem but it might occur, using exceptions enables you to avoid costly testing and so forth.

Well, that’s it. Hope you learned something. Now go and play. And remember the Python motto of learning: use the source (which basically means read all the code you can get your hands on).

Python Reference

This is not a full Python reference by far—you can find that in the standard Python documentation ( http://python.org/doc/ref ). Rather, this is a handy “cheat sheet” that can be useful for refreshing your memory as you start out programming in Python.

Expressions

This section summarizes Python expressions. Table B-1 lists the most important basic (literal) values in Python; Table B-2 lists the Python operators, along with their precedence (those with high precedence are evaluated before those with low precedence); Table B-3 describes some of the most important built-in functions; Tables B-4 through B-6 describe the list methods, dictionary methods, and string methods, respectively. 2

Table B-1. Basic (Literal) Values

Type

Description

Syntax Samples

Integer

Numbers without a fractional part

42

Float

Numbers with a fractional part

42.5 , 42.5e-2

Complex

Sum of a real (integer or float) and imaginary number

38 + 4j , 42j

String

An immutable sequence of characters

'foo' , "bar" , """baz""" , r' '

Table B-2. Operators

Operator

Description

Precedence

lambda

Lambda expression

1

… if … else

Conditional expression

2

or

Logical or

3

and

Logical and

4

not

Logical negation

5

in

Membership test

6

not in

Negative membership test

6

is

Identity test

6

is not

Negative identity test

6

<

Less than

6

>

Greater than

6

<=

Less than or equal to

6

>=

Greater than or equal to

6

==

Equal to

6

!=

Not equal to

6

|

Bitwise or

7

^

Bitwise exclusive or

8

&

Bitwise and

9

<<

Left shift

10

>>

Right shift

10

+

Addition

11

-

Subtraction

11

*

Multiplication

12

@

Matrix multiplication

12

/

Division

12

//

Integer division

12

%

Remainder

12

+

Unary identity

13

-

Unary negation

13

Bitwise complement

13

**

Exponentiation

14

x.attribute

Attribute reference

15

x[index]

Item access

15

x[index1:index2[:index3]]

Slicing

15

f(args…)

Function call

15

(…)

Parenthesized expression or tuple display

16

[…]

List display

16

{key:value, …}

Dictionary display

16

Table B-3. Some Important Built-in Functions

Function

Description

abs(number)

Returns the absolute value of a number.

all(iterable)

Returns True if all the elements of iterable are true; otherwise, it returns False .

any(iterable)

Returns True if any of the elements of iterable are true; otherwise, it returns False .

ascii(object)

Works like repr , but escapes non-ASCII characters.

bin(integer)

Converts an integer to a binary literal, in the form of a string.

bool(x)

Interprets x as a Boolean value, returning True or False .

bytearray([string, [encoding[, errors]]])

Creates a byte array, optionally from a given string, with the specified encoding and error handling.

bytes([string, [encoding[, errors]]])

Similar to bytearray , but returns an immutable bytes object.

callable(object)

Checks whether an object is callable.

chr(number)

Returns a character whose Unicode code point is the given number.

classmethod(func)

Creates a class method from an instance method (see Chapter 7 ).

complex(real[, imag])

Returns a complex number with the given real (and, optionally, imaginary) component.

delattr(object,  name)

Deletes the given attribute from the given object.

dict([mapping-or-sequence])

Constructs a dictionary, optionally from another mapping or a list of (key, value) pairs. May also be called with keyword arguments.

dir([object])

Lists (most of) the names in the currently visible scopes, or optionally (most of) the attributes of the given object.

divmod(a,  b)

Returns (a // b, a % b) (with some special rules for floats).

enumerate(iterable)

Iterates over (index, item) pairs, for all items in iterable . Can supply a keyword argument start , to start somewhere other than zero.

eval(string[,  globals[, locals]])

Evaluates a string containing an expression, optionally in a given global and local scope.

filter(function,  sequence)

Returns a list of the elements from the given sequence for which function returns true.

float(object)

Converts a string or number to a float.

format(value[, format_spec])

Returns a formatted version of the given value, in the form of a string. The specification works the same way as the format string method.

frozenset([iterable])

Creates a set that is immutable, which means it can be added to other sets.

getattr(object,  name[,  default])

Returns the value of the named attribute of the given object, optionally with a given default value.

globals()

Returns a dictionary representing the current global scope.

hasattr(object, name)

Checks whether the given object has the named attribute.

help([object])

Invokes the built-in help system, or prints a help message about the given object.

hex(number)

Converts a number to a hexadecimal string.

id(object)

Returns the unique ID for the given object.

input([prompt])

Returns data input by the user as a string, optionally using a given prompt.

int(object[, radix])

Converts a string (optionally with a given radix) or number to an integer.

isinstance(object, classinfo)

Checks whether the given object is an instance of the given classinfo value, which may be a class object, a type object, or a tuple of class and type objects.

issubclass(class1, class2)

Checks whether class1 is a subclass of class2 (every class is a subclass of itself).

iter(object[, sentinel])

Returns an iterator object, which is object.__iter__() , an iterator constructed for iterating a sequence (if object supports __getitem__ ), or, if sentinel is supplied, an iterator that keeps calling object in each iteration until sentinel is returned.

len(object)

Returns the length (number of items) of the given object.

list([sequence])

Constructs a list, optionally with the same items as the supplied sequence.

locals()

Returns a dictionary representing the current local scope (do not modify this dictionary).

map(function, sequence, …)

Creates a list consisting of the values returned by the given function when applying it to the items of the supplied sequence(s).

max(object1, [object2, …])

If object1 is a nonempty sequence, the largest element is returned; otherwise, the largest of the supplied arguments ( object1 , object2 , . . .) is returned.

min(object1, [object2,  …])

If object1 is a nonempty sequence, the smallest element is returned; otherwise, the smallest of the supplied arguments ( object1 , object2 , . . .) is returned.

next(iterator[, default])

Returns the value of iterator.__next__() , optionally providing a default if the iterator is exhausted.

object()

Returns an instance of object , the base class for all (new-style) classes.

oct(number)

Converts an integer number to an octal string.

open(filename[,  mode[,  bufsize]])

Opens a file and returns a file object. (Has additional optional arguments, e.g., for encoding and error handling.)

ord(char)

Returns the Unicode code point of a single character.

pow(x, y[,  z])

Returns x to the power of y , optionally modulo z .

print(x, …)

Print out a line containing zero or more arguments to standard output, separated by spaces. This behavior may be adjusted with the keyword arguments sep , end , file , and flush .

property([fget[,  fset[,  fdel[, doc]]]])

Creates a property from a set of accessors (see Chapter 9 ).

range([start, ]stop[,  step])

Returns a numeric range (a form of sequence) with the given start (inclusive, default 0), stop (exclusive), and step (default 1).

repr(object)

Returns a string representation of the object, often usable as an argument to eval .

reversed(sequence)

Returns a reverse iterator over the sequence.

round(float[,  n])

Rounds off the given float to n digits after the decimal point (default zero). For detailed rounding rules, consult the official documentation.

set([iterable])

Returns a set whose elements are taken from iterable (if given).

setattr(object, name, value)

Sets the named attribute of the given object to the given value.

sorted(iterable[, cmp][, key][, reverse])

Returns a new sorted list from the items in iterable . Optional parameters are the same as for the list method sort .

staticmethod(func)

Creates a static (class) method from an instance method (see Chapter 7 ).

str(object)

Returns a nicely formatted string representation of the given object.

sum(seq[, start])

Returns the sum of a sequence of numbers, added to the optional parameter start (default 0).

super([type[, obj/type]])

Returns a proxy that delegates method calls to the superclass.

tuple([sequence])

Constructs a tuple, optionally with the same items as the supplied sequence.

type(object)

Returns the type of the given object.

type(name,  bases, dict)

Returns a new type object with the given name, bases, and scope.

vars([object])

Returns a dictionary representing the local scope, or a dictionary corresponding to the attributes of the given object (do not modify the returned dictionary).

zip(sequence1, …)

Returns an iterator of tuples, where each tuple contains an item from each of the supplied sequences. The returned list has the same length as the shortest of the supplied sequences.

Table B-4. List Methods

Method

Description

aList.append(obj)

Equivalent to aList[len(aList):len(aList)] = [obj] .

aList.clear()

Removes all elements from aList .

aList.count(obj)

Returns the number of indices i for which aList[i] == obj .

aList.copy()

Returns a copy of aList . Note that this is a shallow copy, so the elements are not copied.

aList.extend(sequence)

Equivalent to aList[len(aList):len(aList)] = sequence .

aList.index(obj)

Returns the smallest i for which aList[i]  == obj (or raises a ValueError if no such i exists).

aList.insert(index, obj)

Equivalent to aList[index:index] = [obj] if index  >= 0 ; if index  < 0 , object is prepended to the list.

aList.pop([index])

Removes and returns the item with the given index (default –1).

aList.remove(obj)

Equivalent to del  aList[aList.index(obj)] .

aList.reverse()

Reverses the items of aList in place.

aList.sort([cmp][, key][, reverse])

Sorts the items of aList in place (stable sorting). Can be customized by supplying a comparison function, cmp ; a key function, key , which will create the keys for the sorting); and a reverse flag (a Boolean value).

Table B-5. Dictionary Methods

Method

Description

aDict.clear()

Removes all the items of aDict .

aDict.copy()

Returns a copy of aDict .

aDict.fromkeys(seq[, val])

Returns a dictionary with keys from seq and values set to val (default None ). May be called directly on the dictionary type, dict , as a class method.

aDict.get(key[, default])

Returns aDict[key] if it exists; otherwise, it returns the given default value (default None ).

aDict.items()

Returns an iterator (actually, a view ) of (key, value) pairs representing the items of aDict .

aDict.iterkeys()

Returns an iterable object over the keys of aDict .

aDict.keys()

Returns an iterator (view) of the keys of aDict .

aDict.pop(key[, d])

Removes and returns the value corresponding to the given key, or the given default, d .

aDict.popitem()

Removes an arbitrary item from aDict and returns it as a (key, value) pair.

aDict.setdefault(key[, default])

Returns aDict[key] if it exists; otherwise, it returns the given default value (default None ) and binds aDict[key] to it.

aDict.update(other)

For each item in other , adds the item to aDict (possibly overwriting existing items). It can also be called with arguments similar to the dictionary constructor, aDict .

aDict.values()

Returns an iterator (view) of the values in aDict (possibly containing duplicates).

Table B-6. String Methods

Method

Description

string.capitalize()

Returns a copy of the string in which the first character is capitalized.

string.casefold()

Returns a string that has been normalized in a manner similar to simple lowercasing, more suitable for case-insensitive comparisons between Unicode strings.

string.center(width[, fillchar])

Returns a string of length max(len(string), width ) in which a copy of string is centered, padded with fillchar (the default is space characters).

string.count(sub[, start[, end]])

Counts the occurrences of the substring sub , optionally restricting the search to string[start:end] .

string.encode([encoding[, errors]])

Returns the encoded version of the string using the given encoding, handling errors as specified by errors ( 'strict' , 'ignore' , or 'replace' , among other possible values).

string.endswith(suffix[, start[, end]])

Checks whether string ends with suffix , optionally restricting the matching with the given indices start and end .

string.expandtabs([tabsize])

Returns a copy of the string in which tab characters have been expanded using spaces, optionally using the given tabsize (default 8).

string.find(sub[, start[, end]])

Returns the first index where the substring sub is found, or –1 if no such index exists, optionally restricting the search to string[start:end] .

string.format(…)

Implements the standard Python string formatting. Brace-delimited fields in string are replaced by the corresponding arguments, and the result is returned.

string.format_map(mapping)

Similar to using format with keyword arguments, except the arguments are provided as a mapping.

string.index(sub[, start[, end]])

Returns the first index where the substring sub is found, or raises a ValueError if no such index exists, optionally restricting the search to string[start:end] .

string.isalnum()

Checks whether the string consists of alphanumeric characters.

string.isalpha()

Checks whether the string consists of alphabetic characters.

string.isdecimal()

Checks whether the string consists of decimal characters.

string.isdigit()

Checks whether the string consists of digits.

string.isidentifier()

Checks whether the string could be used as a Python identifier.

string.islower()

Checks whether all the case-based characters (letters) of the string are lowercase.

string.isnumeric()

Checks whether the string consists of numeric characters.

string.isprintable()

Checks whether the string consists of printable characters.

string.isspace()

Checks whether the string consists of whitespace.

string.istitle()

Checks whether all the case-based characters in the string following non-case-based letters are uppercase and all other case-based characters are lowercase.

string.isupper()

Checks whether all the case-based characters of the string are uppercase.

string.join(sequence)

Returns a string in which the string elements of sequence have been joined by string .

string.ljust(width[, fillchar])

Returns a string of length max(len(string), width) in which a copy of string is left-justified, padded with fillchar (the default is space characters).

string.lower()

Returns a copy of the string in which all case-based characters have been lowercased.

string.lstrip([chars])

Returns a copy of the string in which all chars have been stripped from the beginning of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).

str.maketrans(x[, y[, z]])

A static method on str . Constructs a translation table for translate , using a mapping x from characters or ordinals to Unicode ordinals (or None for deletion). Can also be called with two strings representing the from- and to-characters, and possibly a third, with characters to be deleted.

string.partition(sep)

Searches for sep in the string and returns (head, sep, tail) .

string.replace(old, new[, max])

Returns a copy of the string in which the occurrences of old have been replaced with new , optionally restricting the number of replacements to max .

string.rfind(sub[, start[, end]])

Returns the last index where the substring sub is found, or –1 if no such index exists, optionally restricting the search to string[start:end] .

string.rindex(sub[, start[, end]])

Returns the last index where the substring sub is found, or raises a ValueError if no such index exists, optionally restricting the search to string[start:end] .

string.rjust(width[, fillchar])

Returns a string of length max(len(string), width) in which a copy of string is right-justified, padded with fillchar (the default is space characters).

string.rpartition(sep)

Same as partition , but searches from the right.

string.rstrip([chars])

Returns a copy of the string in which all chars have been stripped from the end of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).

string.rsplit([sep[, maxsplit]])

Same as split , but when using maxsplit , counts from right to left.

string.split([sep[, maxsplit]])

Returns a list of all the words in the string, using sep as the separator (splits on all whitespace if left unspecified), optionally limiting the number of splits to maxsplit .

string.splitlines([keepends])

Returns a list with all the lines in string , optionally including the line breaks (if keepends is supplied and is true).

string.startswith(prefix[, start[, end]])

Checks whether string starts with prefix , optionally restricting the matching with the given indices start and end .

string.strip([chars])

Returns a copy of the string in which all chars have been stripped from the beginning and the end of the string (the default is all whitespace characters, such as spaces, tabs, and newlines).

string.swapcase()

Returns a copy of the string in which all the case-based characters have had their case swapped.

string.title()

Returns a copy of the string in which all the words are capitalized.

string.translate(table)

Returns a copy of the string in which all characters have been translated using table (constructed with maketrans ).

string.upper()

Returns a copy of the string in which all the case-based characters have been uppercased.

string.zfill(width)

Pads string on the left with zeros to fill width (with any initial + or - moved to the beginning).

Statements

This section gives you a quick summary of each of the statement types in Python.

Simple Statements

Simple statements consist of a single (logical) line.

Expression Statements

Expressions can be statements on their own. This is especially useful if the expression is a function call or a documentation string.

Example:

"This module contains SPAM-related functions."

Assert Statements

Assert statements check whether a condition is true and raise an AssertionError (optionally with a supplied error message) if it isn’t.

Example:

assert age >= 12, 'Children under the age of 12 are not allowed'

Assignment Statements

Assignment statements bind variables to values. Multiple variables may be assigned to simultaneously (through sequence unpacking), and assignments may be chained.

Examples:

x = 42                      # Simple assignment
name, age = 'Gumby', 60     # Sequence  unpacking
x = y = z = 10              # Chained assignments

Augmented Assignment Statements

Assignments may be augmented by operators. The operator will then be applied to the existing value of the variable and the new value, and the variable will be rebound to the result. If the original value is mutable, it may be modified instead (with the variable staying bound to the original).

Examples:

x *= 2        # Doubles x
x += 5        # Adds 5 to x

The pass Statement

The passstatement is a “no-op,” which does nothing. It is useful as a placeholder, or as the only statement in syntactically required blocks where you want no action to be performed.

Example:

try: x.name
except AttributeError: pass
else: print('Hello', x.name)

The del Statement

The delstatement unbinds variables and attributes and removes parts (positions, slices, or slots) from data structures (mappings or sequences). It cannot be used to delete values directly, because values are deleted only through garbage collection.

Examples:

del x             # Unbinds a variable
del seq[42]       # Deletes a sequence element
del seq[42:]      # Deletes a sequence slice
del map['foo']    # Deletes a mapping item

The return Statement

The returnstatement halts the execution of a function and returns a value. If no value is supplied, None is returned.

Examples:

return              # Returns None from the current function
return 42           # Returns 42 from the current function
return 1, 2, 3      # Returns (1, 2, 3) from the current function

The yield Statement

The yieldstatement temporarily halts the execution of a generator and yields a value. A generator is a form of iterator and can be used in for loops, among other things.

Example:

yield 42      # Returns 42 from the current function

The raise Statement

The raisestatement raises an exception. It may be used without any arguments (inside an except clause, to re-raise the currently caught exception), with a subclass of Exception and an optional argument (in which case, an instance is constructed) or with an instance of a subclass of Exception .

Examples:

raise # May only be used inside except clauses
raise IndexError
raise IndexError, 'index out of bounds'
raise IndexError('index out of bounds')

The break Statement

The breakstatement ends the immediately enclosing loop statement ( for or while ) and continues execution immediately after that loop statement.

Example:

while True:
    line = file.readline()
    if not line: break
    print(line)

The continue Statement

The continuestatement is similar to the break statement in that it halts the current iteration of the immediately enclosing loop, but instead of ending the loop completely, it continues execution at the beginning of the next iteration.

Example:

while True:
    line = file.readline()
    if not line: break
    if line.isspace(): continue
    print(line)

The import Statement

The importstatement is used to import names (variables bound to functions, classes, or other values) from an external module. This also covers from __future__ import … statements for features that will become standard in future versions of Python.

Examples:

import math
from math import sqrt
from math import sqrt as squareroot
from math import *

The global Statement

The globalstatement is used to mark a variable as global. It is used in functions to allow statements in the function body to rebind global variables. Using the global statement is generally considered poor style and should be avoided whenever possible.

Example:

count = 1
def inc():
    global count
    count += 1

The nonlocal Statement

This is similar to the globalstatement but refers to an outer scope of an inner function (a closure). That is, if you define a function inside another function and return it, this inner function may refer to—and modify—variables from the outer function, provided they are marked as nonlocal.

Example:

def makeinc():
    count = 1
    def inc():
        nonlocal count
        count += 1
    return inc

Compound Statements

Compound statements contain groups (blocks) of other statements.

The if Statement

The if statement is used for conditional execution, and it may include elif and else clauses.

Example:

if x < 10:
    print('Less than ten')
elif 10 <= x < 20:
    print('Less than twenty')
else:
    print('Twenty or more')

The while Statement

The whilestatement is used for repeated execution (looping) while a given condition is true. It may include an else clause (which is executed if the loop finishes normally, without any break or return statements, for instance).

Example:

x = 1
while x < 100:
    x *= 2
print(x)

The for Statement

The for statement is used for repeated execution (looping) over the elements of sequences or other iterable objects (objects having an __iter__ method that returns an iterator). It may include an else clause (which is executed if the loop finishes normally, without any break or return statements, for instance).

Example:

for i in range(10, 0, -1):
    print(i)
print('Ignition!')

The try Statement

The trystatement is used to enclose pieces of code where one or more known exceptions may occur and enables your program to trap these exceptions and perform exception-handling code if an exception is trapped. The try statement can combine several except clauses (handling exceptional circumstances) and finally clauses (executed no matter what; useful for cleanup).

Example:

try:
    1 / 0
except ZeroDivisionError:
    print("Can't divide anything by zero.")
finally:
    print("Done trying to calculate 1 / 0")

The with Statement

The with statement is used to wrap a block of code using a so-called context manager, allowing the context manager to perform some setup and cleanup actions. For example, files can be used as context managers, and they will close themselves as part of the cleanup.

Example:

with open("somefile.txt") as myfile:
    dosomething(myfile)
# The file will have been closed here

Function Definitions

Function definitions are used to create function objects and to bind global or local variables to these function objects.

Example:

def double(x):
    return x * 2

Class Definitions

Class definitions are used to create class objects and to bind global or local variables to these class objects.

Example:

class Doubler:
    def __init__ (self, value):
        self.value = value
    def double(self):
        self.value *= 2

Index

A

  1. Abstract base class

  2. Abstraction

  3. add function

  4. Algorithm

  5. and operator

SeeBoolean operators
  1. Arcade game

    1. goals

    2. implementation

      1. falling weights animation (weights.py)

      2. game over screen

      3. level cleared screen

      4. main game module (squish.py)

      5. Squish configuration file (config.py)

      6. Squish game objects

      7. Squish opening screen

      8. squish.py file

      9. steps

      10. weights.py and weight.png

    3. preparations

    4. preparations weight and banana graphics

    5. pygame module

      1. pygame.display module

      2. pygame.font module

      3. pygame.image module

      4. pygame.locals module

      5. pygame.mouse module

      6. pygame.sprite module

  2. Arguments

    1. print multiple

  3. Assert statements

  4. Assignment statement

    1. augmented assignments

    2. chained assignments

    3. sequence unpacking

  5. Asynchronous I/O

  6. AttributeError

  7. Attributes

  8. Augmented assignments

B

  1. Basket constructor

  2. Binary search

  3. Blocking network programming

  4. Blocks

  5. Boolean function

  6. Boolean operators

  7. Boolean values

  8. Boost.Python

  9. Break statement

  10. Built-in exceptions

  11. Built-in functions

  12. Bulletin board

    1. database creation

      1. MySQL

      2. PostgreSQL

      3. SQLite

    2. database structure

    3. implementation

      1. CGI scripts

      2. Content-type string

      3. core functionality

      4. database-handling code figured out

      5. edit script writing

      6. formatting code

      7. main page

      8. main script writing

      9. message composer

      10. message viewer

      11. save.cgi script

      12. simple_main.cgi

      13. structuring web programs

      14. testing purposes

      15. view.cgi script

    4. requirements

    5. tools

  13. bytearray

  14. Bytes

C

  1. C API

  2. Catching exceptions

  3. Catching object

  4. C extensions

  5. Chained assignments

  6. Character sets

  7. ChatServer class

  8. Class

    1. abstract base

    2. create new

    3. definitions

    4. namespace

    5. subclass

    6. superclass

  9. Client/server pair

  10. Client sockets

  11. Close method

  12. Closing files

  13. cmath and complex numbers

  14. Colon (:)

  15. Comment

  16. Common Gateway Interface (CGI)

    1. cgi module

    2. cgitb

    3. file permissions

    4. HTML forms

    5. pound bang line

    6. security risks

    7. web server

  17. Comparing incompatible types

  18. Comparison operators

  19. Compilation process

    1. gcc

    2. SWIG

  20. Compiling extensions

  21. Comprehensions

  22. Conditional execution

    1. elif clauses

    2. else clauses

    3. if statement

    4. nesting blocks

  23. Connections, Python DB API

  24. Constructors

    1. _ _init_ _

    2. init method

    3. overriding methods

    4. parameters

    5. super function

    6. unbound superclass constructor

  25. Content handler

  26. Context managers

  27. continue statement

  28. Conversion specifiers

  29. count method

  30. CounterList class

  31. ctypes module

  32. Cursors, Python DB API

  33. Cython

D

  1. Data structure

  2. Decorators

  3. Default mode

  4. Defaults

  5. def statement

SeeFunctions, definition
  1. del statement

  2. Dictionary

    1. database

    2. dict function

    3. methods

      1. clear

      2. copy

      3. fromkeys

      4. get

      5. items

      6. keys

      7. pop

      8. popitem

      9. setdefault

      10. update

      11. values

    4. operations

    5. string formatting

  3. Docstring

  4. doctest

E

  1. Eight Queens problem

    1. base case

    2. conflicts

    3. generators and backtracking

    4. prettyprint

    5. problem

    6. recursive case

    7. solutions

    8. state representation

  2. elif clauses

  3. else clauses

  4. Encapsulation

  5. Environment variables

  6. Equality operator

  7. Error message

  8. eval function

  9. Event handling

  10. except clause

  11. Exceptions

    1. built-in

    2. catching

    3. custom classes

    4. definition

    5. and functions

    6. raise statement

    7. with one block

    8. zen of

  12. exec function

  13. Exploring modules

    1. _ _all_ _ variable

    2. dir function

    3. documentation

    4. help

    5. Python interpreter

    6. source code

  14. Expression statements

  15. Extensions

    1. PyArg_ParseTuple

    2. SWIG and Cython

F

  1. Factorial (of number)

  2. Fibonacci numbers

  3. fibs function

  4. Fictitious function

  5. FileExistsError

  6. fileinput module

  7. File-like object

  8. File(s)

    1. closing files

    2. context managers

    3. file-like object

    4. iterating over file contents

    5. iterators

    6. modes

    7. modified text file

    8. objects

    9. opening files

    10. Piping Output

    11. random access

    12. reading and writing

    13. reading and writing lines

    14. standard streams

    15. somefile.txt

    16. streams

  9. File sharing, GUI

    1. implementation

      1. fetch method

      2. finished GUI client (guiclient.py)

      3. ListableNode

      4. simple GUI client (simple_guiclient.py)

    2. preparations

    3. requirements

    4. tools

  10. File sharing, XML-RPC

    1. client-server interaction

    2. implementation

      1. _broadcast method

      2. client interface creation

      3. command

      4. file test.txt

      5. new node implementation (server.py)

      6. node controller interface (client.py)

      7. raising exceptions

      8. register_instance method

      9. simple node

      10. SimpleXMLRPCServer class

      11. validating file names

    3. peer-to-peer system

    4. preparation

    5. requirements

    6. standard library modules

  11. Filter class

  12. filterwarnings function

  13. Finally clause

  14. Flask

  15. Food Database Query program

  16. Forking server

  17. for loops

  18. Formal parameters

  19. for statement

  20. Foundations of Python Network Programming

  21. Friends and SocketServer

  22. Functions

    1. add

    2. definition

    3. document

    4. eval

    5. exec

    6. fibs

    7. filter

    8. isinstance

    9. map

    10. return statement

    11. store

G

  1. Garbage collection

  2. Generators

    1. comprehension

    2. definition

    3. flatten generator

    4. generator-function and generator-iterator

    5. making

    6. methods

    7. recursive

    8. simulating

  3. Geometry manager

  4. _ _getattr_ _ method

  5. Global variables

  6. Graphical user interfaces (GUIs)

    1. elements

    2. event handling

    3. file sharing

SeeFile sharing, GUI
  1. initial exploration

  2. layout

  3. mechanisms

  4. object-oriented design

  5. text editor

  6. Tkinter

H

  1. Handlers

  2. heapify function

  3. heappop function

  4. heapreplace function

  5. Heaps

  6. Hexadecimals and octals

I

  1. Identity operator

  2. if statement

  3. Import something from module

  4. import statement

  5. in operator

SeeMembership operator
  1. IndexError

  2. Infinite recursion

  3. Inheritance

  4. Input from user

  5. Installation process

  6. Interfaces

  7. Interpreter

  8. Introspection

  9. IronPython

  10. is operator

SeeIdentity operator
  1. isinstance function

  2. Item access

    1. sequences and mappings

SeeSequences and mappings protocol
  1. subclassing list, dict, and str

  1. Iteration

    1. iterating over file contents

      1. fictitious function

      2. fileinput

      3. file iterators

      4. one character (or byte) at time

      5. one line at time

      6. process

      7. reading everything

    2. numbered

    3. parallel

    4. reversed and sorted iteration

  2. Iterators

    1. list constructor

    2. protocol

    3. sequences making

  3. _ _iter_ _ method

J

  1. Jujitsu of programming

  2. Jython

K

  1. KeyError

  2. Keyword arguments

  3. Keyword parameters

L

  1. Lambda expressions

  2. Layout

  3. Lazy evaluation

  4. LinePlot class

  5. LineReceiver class

  6. Linux system

  7. Lists

    1. deleting elements

    2. function

    3. item assignments

    4. method

      1. append

      2. clear

      3. copy

      4. count

      5. extend

      6. index

      7. insert

      8. pop

      9. remove

      10. reverse

      11. sort

    5. operations

    6. slicing

  8. Literal values

  9. Local variables

  10. Loops

    1. break

    2. continue

    3. dictionary

    4. else clauses

    5. for loops

    6. while loops

    7. while True/break idiom

M

  1. Markup system

    1. handlers (handlers.py)

    2. implementation

      1. action method

      2. constructing, rules and filters

      3. filters

      4. finding blocks of text

      5. handler

      6. handler superclass

      7. Parser class

      8. rules

      9. script creation

      10. web page generating

    3. LATEX

    4. main program (markup.py)

    5. plain-text file

    6. preparations

    7. rules (rules.py)

    8. tools

  2. match function

  3. Membership operator

  4. Method resolution order (MRO)

  5. Methods, attributes, functions, and

  6. Minimal client

  7. Minimal server

  8. Modules

    1. clientdb and billing code

    2. conditional test code

    3. define things

    4. exploring

SeeExploring modules
  1. function defining

  2. importlib module

  3. interpreter

  4. packages

  5. packaging.python.org

  6. problematic test code

  7. program

  8. PYTHONPATH environment variable

  9. sys module

  10. test code adding

  1. Multiple inheritance

N

  1. NameError

  2. Namespace

  3. Nesting

  4. Nesting blocks

  5. Networking modules

    1. asynchronous I/O

    2. blocking or synchronous network programming

    3. CGI

    4. forking and threading

    5. friends

    6. multiple connections

    7. network-related modules in standard library

    8. opening remote files

    9. retrieving remote files

    10. select and poll

    11. selection

    12. socket module

    13. SocketServer framework

    14. standard library

    15. Twisted

    16. urllib

    17. URLs

  6. Network News Transfer Protocol (NNTP)

  7. News gathering agent

    1. implementation

      1. addSource and addDestination

      2. getItems and receiveItems

      3. methods

      4. NewsAgent

      5. newsagent2.py

      6. news.html page

      7. NewsItem

      8. news page generated

      9. nntplib

      10. NNTP server

      11. NNTPSource

      12. PlainDestination

      13. simple news-gathering agent

      14. SimpleWebSource

    2. preparations

    3. servers

    4. tools

    5. urllib

  8. NNTP

SeeNetwork News Transfer Protocol (NNTP)
  1. Nonsensical text

  2. Numbered iteration

  3. Numbers and expressions

  4. NumPy module

O

  1. Object-oriented programming

  2. Object-relational mappers

  3. Objects

    1. encapsulation

    2. inheritance

    3. polymorphism

  4. One character (or byte) at a time

  5. One line at a time

  6. open function

  7. Operators

    1. * and **

    2. Boolean

    3. comparison

    4. equality

    5. identity

    6. membership

  8. OSError

  9. os Module

  10. Overriding methods

P, Q

  1. Packages

  2. Pack manager

  3. Palindrome

  4. Parallel iteration

  5. Parameters

    1. actual

    2. change

    3. collect

    4. formal

    5. keyword

    6. positional

    7. practice

    8. style

    9. wrapping

  6. Parse method

  7. pass statement

  8. Piping Output

  9. Plain-text markup

  10. Playful Programming

    1. configuration files

    2. extracting constants

    3. jujitsu

    4. logging

    5. prototyping

  11. Polymorphism

    1. definition

    2. forms

    3. interface

    4. methods

    5. term

  12. popitem method

  13. Positional parameters

  14. Power

  15. Pretty picture painting

    1. crucial tool

    2. file-handling and string-processing facilities

    3. implementation

      1. data getting

      2. LinePlot class

      3. PolyLine

      4. prototype

      5. ReportLab

      6. sunspot graph

    4. preparations

    5. program

    6. sunspot program (sunspots.py)

  16. profile

  17. Properties, magic methods

    1. accessor methods

    2. _ _getattr_ _and _ _setattr_ _

    3. get_size and set_size methods

    4. property function

    5. Rectangle class

    6. static methods and class methods

  18. property function

  19. Prototyping

  20. _ _pycache_ _

  21. PyChecker

  22. PyCXX

  23. py2exe extension

  24. PyLint

  25. PyPy

  26. PySQLite

  27. Python

    1. abstraction

    2. conditional expressions

    3. control structures

    4. DB API

      1. connections

      2. cursors

      3. exceptions

      4. global variables

      5. Specification v2.0

      6. SQLite and PySQLite

      7. types and special values

    5. dictionaries

    6. exceptions

    7. for loop iterates

    8. function

    9. input function

    10. module/script

    11. objects and stuff

    12. == operator

    13. standard library modules

    14. user interaction

  28. Python 3

  29. Python Library Reference

R

  1. raise statement

  2. Random access

  3. Random module

  4. Reading and writing, files

  5. Reading and writing lines

  6. Rectangle class

  7. Recursion

    1. binary search

    2. definition

    3. factorial

    4. infinite

    5. power

  8. Recursive generator

  9. Reference counting

  10. Regular expression

  11. Remote editing, CGI

    1. implementation

      1. editor running

      2. editor script writing

      3. file name form, creation

      4. prototype

      5. save script writing

      6. simple_edit.cgi script

      7. simple web editor

    2. preparations

    3. requirements

    4. tools

  12. ReportLab program

  13. Representational state transfer (REST)

  14. Retrieving remote files

  15. return statement

  16. Reversed and sorted iteration

  17. Rich Site Summary (RSS)

  18. RPC

  19. Rule superclass

S

  1. Saving and executing program

    1. command prompt

    2. IDLE

    3. making executable program

    4. print statement

  2. SAX programming

  3. Scope, dictionary

  4. Screen scraping

    1. Beautiful Soup

    2. HTMLParser

    3. Tidy

    4. urllib and re

    5. XHTML

  5. Select and poll, asynchronous I/O with

  6. Sequence

    1. adding

    2. comparisons

    3. indexing

    4. len, min, and max

    5. longer steps

    6. membership

    7. multiplying

    8. nifty shortcut

    9. none, empty lists and initialization

    10. slicing

    11. unpacking

  7. Sequences and mappings protocol

    1. arithmetic sequence

    2. collections module

    3. _ _delitem_ _(self, key)

    4. _ _getitem_ _(self, key)

    5. _ _len_ _ method

    6. _ _len_ _(self)

    7. requirements

    8. _ _setitem_ _(self, key, value)

    9. TypeError

  8. Server socket

  9. _ _setattr_ _ method

  10. Sets module

  11. Setuptools

  12. Shape class

  13. Short-circuit logic

  14. Simple node implementation (simple_node.py)

  15. SimpleWebSource

  16. SIP

  17. SOAP

  18. Socket module

  19. SocketServer framework

  20. somefile.txt file

  21. somescript.py

  22. Sorting

  23. SPAMFilters

  24. SQLite

    1. advantages

    2. creating and populating tables

    3. definition

    4. and PySQLite

    5. Python standard library

    6. sample database application

    7. searching and dealing

  25. Standard library

    1. deques

    2. email headers

    3. fileinput module

    4. finding sender, email

    5. group numbers and functions

    6. heappush function

    7. heaps

    8. match objects and groups

    9. os module

    10. random

    11. regular expression

      1. alternatives and subpatterns

      2. character sets

      3. escaping special characters

      4. optional and repeated subpatterns

      5. string

      6. wildcard

    12. re module

      1. functions

      2. MatchObject

      3. maxsplit argument

      4. re.escape

      5. re.split

      6. re.sub

    13. sets module

    14. shelve and json

    15. simple database application

    16. standard modules

    17. sys module

    18. template system

    19. time module

  26. Standard streams

  27. Statements

    1. assert

    2. assignment

    3. augmented assignment

    4. break

    5. compound

    6. continue

    7. del

    8. expressions

    9. for statement

    10. global

    11. if statement

    12. import

    13. pass

    14. raise

    15. return

    16. simple

    17. try

    18. while

    19. with statement

    20. yield

  28. store function

  29. Streams

  30. String(s)

    1. bytearray

    2. bytes

    3. concatenating strings

    4. conversions

    5. conversion specifiers

    6. double quotes

    7. escaping quotes

    8. f-strings

    9. keyword arguments

    10. long string

    11. methods

      1. center

      2. find

      3. join

      4. lower

      5. replace

      6. split

      7. strip

      8. title

      9. translate

    12. operations

    13. operator

    14. raw string

    15. replacement field names

    16. and sequence comparisons

    17. signs, alignment, and zero-padding

    18. single quotes

    19. str and repr

    20. unicode

    21. width, precision, and thousands separators

  31. Structure

  32. Structure computer programs

  33. Subclass

  34. subprocess module

  35. Sunspot graph

  36. Superclass

  37. Super function

  38. SWIG

  39. Synchronous network programming

  40. SyntaxError

  41. sys module

T

  1. Test-driven programming

  2. Testing

    1. coverage

    2. debugging

    3. doctest

    4. requirement specification

    5. test-driven programming

    6. unittest

  3. Text Block generator

  4. Threading server

  5. threadsafety

  6. thread-safety level

  7. throw method

  8. Tkinter

  9. Traceback

  10. Transmitting data

  11. try/except statement

  12. Tuples

  13. Twisted framework

    1. common GUI toolkits

    2. downloading and installing

    3. event-driven networking framework

    4. in Python 2

    5. server

  14. Twisted Matrix Laboratories

  15. TypeError

U

  1. Unicode

  2. Uniform Resource Locator (URL)

  3. United States Department of Agriculture (USDA)

  4. Unit tests (unittest)

    1. profiler module

    2. PyChecker

    3. PyLint

  5. Universal newline mode

  6. UNIX system

  7. urandom function

  8. urllib module

  9. urllib2 module

  10. Usenet

V

  1. ValueError

  2. Variables

  3. vars function

  4. Virtual tea party

    1. asyncore framework

    2. chatserver.py

    3. implementation

      1. ChatServer class

      2. ChatSession class

      3. command interpretation

      4. login and logout rooms

      5. main chat room

      6. rooms

      7. simple chat server

    4. preparations

    5. tools

W

  1. warnings module

  2. Weave tool

  3. Web framework

    1. application

    2. powers.py

  4. Web services

    1. REST

    2. RPC

    3. RSS

    4. SOAP

  5. while loops

  6. while statement

  7. while True/break idiom

  8. with statement

X

  1. XML

    1. implementation

      1. default handling

      2. directories support

      3. dispatcher mix-in class

      4. event handlers

      5. header and footer

      6. HTML pages, creation

      7. simple content handler

      8. web site constructor (website.py)

    2. page maker script

    3. preparations

    4. project goals

    5. SAX mechanism

    6. tools

    7. web site represented

Y

  1. yield statement

Z

  1. Zen of exceptions

  2. ZeroDivisionError

  3. Zeroth character

  4. zip function

Footnotes

1 Or any other iterable object, actually.

2 Though commonly referred to as built-in functions, some of the entries in Table B-3 are actually classes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset