HOME Python Post Messages

Python Quick Look


Preface

This document overviews Python using top-down method. A tutorial with a top-down method is feasible using the advantage of HTML that it can link to any resources on the web. The document shows the general features first and then goes into the details step by step. You can stop reading at the place where you get tired.

Python is getting popular and there are several good introductions on the web. Among them, the official documents such as the tutorial, the library reference, and the language reference are most useful. This page is, actually, a collection of links to the official documents. As the official documents have huge volume, links to frequently used features and library is useful. I use (the Japanese version of) this page most frequently among documents I wrote. I hope it is also useful for you.

Contents

  1. Executing Python
  2. The Form of Python Scripts
  3. Assignment
  4. Blocks
  5. IO
  6. Functions
  7. Classes
  8. Data Types
  9. Operators
  10. Library Tour
  11. Appendix

1. Executing Python

First, include the directory where Python executable is to the PATH environmental variable.
Then type like as follow from the prompt to execute Python.
python option   script   argvs 
If you type just "python", the interactive mode is invoked, which is convenient to test each function.

Followings show the command line option.

python [-diOStuUvx?] [-c command | script | - ] [argvs]
Option Effect
-d Output debugging information.
-i Check the script interactively and show the prompt.
-O Optimise the byte code.
-S Ignore import statement.
-t Warn contradicting indent.
-u Use non-buffered binary standard output and standard error.
-U Read String literals as Unicode.
-v Detailed tracking of import statement.
-x Skip the first line of the source code.
-? Help.
-c command
Execute the specified command.
script
Read and execute a python source file.
argvs
Arguments of the script or command.
When Python is exuecuted as the interactive mode, it read a file specified by PYTHONSTARTUP environmental variable. It is convenient to importing often used modules using this file. See
Tutorial 2.2.4 for detailed information.

Example of the start up file:

01:     # PYTHONSTARTUP
02:     
03:     import sys, math, re, os, os.path
04:     print 'sys, math, re, os, os.path has been imported.'

2. The Form of Python Scripts

Following code shows an example of a Python script
00:     #! /usr/bin/env python
01:     # -*- coding: iso-8859-1  -*-
02:     
03:     r"""
04:     Comments on the script
05:     Comment 1:
06:     Comment 2:
07:     """
08:     import string
09:     from datetime import date
10:     import tkinter as tk
11:     
12:     #function
13:     def sum(ls):
14:         """ returns sum of list items"""
15:         s=0
16:         for x in ls:
17:             s+=x
18:         return s
19:     
20:     class MyClass:
21:         """My class"""
22:         def __init__(self, p1, p2):
23:             self.p1 = p1
24:             self.p2 = p2
25:     
26:         def show_p1(self):
27:             return self.p1
28:     
29:         def show_p2(self):
30:             return self.p2
31:     
32:     if __name__ == '__main__':
33:         print sum([x*x for x in range(10)]
Line
01:
This line specifies the program to execute the script. This line is valid on UNIX like system and ignored on others such as Windows and Mac. The script can be executed by script instead of python script after chmod +x script. It is recommended to add this line for portability even if the script is not executed on UNIX like system. Parts starting from '#' to the end of line are comments. Lines one and two are special comments.
02:
This line specifies the character set. Character sets iso-8859-N or utf-8 are used for Europian languages.
03 – 06:
This is the explaination on the code. String literals quoted by """ are accepted as they are. The pydoc generates the document of the source code like this automatically using comments at the top of the code, or beginning of class and function difinitions.
08 – 10:
These are statements for import modules. Python has a large library like C and C++ and most of functions, classes, constants are definec in the library (module). There are four ways to import a module:
  1. import module
  2. from module import name
  3. import module as nickname
  4. from module import *
The first way imports all the names [note 1] defined in the module. Write module.name to use the name defined in the module.

The second way imports the name only from the name. In this case, name can be used without specifing the module.

The third way is basically the same as the first way. nickname is used to specify the module. Write nickname.name to use the name.

The fourth way imports all the names of the module and the name can be used without specifing the module name. This way is not recommended as Python uses same function names in many modules. If you are lazy to add the module name, give a short nickname to the module name and use the third way.

import os.path as path
import Tkinter as tk
13 – 18:
This is a function difinition. See Chapter 5.
20 – 30:
This is a class difinition. See Chapter 6.
32 – 33:
When the script is invoked directly, Line 33 is executed. Line 32 is the charm to use this feature. As line 33 is not executed when the script is imported, the feature is convenient to test each function interactively.

3. Assignment

First I will explain about assignment because assignment appears everywhere in Python and I cannot explain anything without it.

The assignment in Python is basically similar to that of the C language. The '=' is used as the assignment operator. The operator assigns the right side value to the left side variable. The difference from the C language is that the assignment statements don't return values. Thus, you cannot write like as follows.

c=1
if 0==(a=c):
    print 'a = 0'
else:
    print 'a = 1'
On the other hand, Python supports structured assignment. This feature is useful in many cases.
a, b, c = 1, 2, 3
(a, (b, c)) = (10, (20, 30))

4. Block

The block of Python starts with colon (':') and increment of indent and ends with decrement of the indent to the original amount. Blocks are used in class and function difinitions, branchings, and loops.

4.1. Branching (if, elif, else)

The if block is used for branching like as follows.
if test:
    then_block
elif test_elif:
    elif_block
else:
    else_block
First the test clause is evaluated and the then_block is evaluated if the test is true. If not, test_elif is evaluated and the elif_block is evaluated if the test_elif is true. Otherwise the else_block is evaluated.

Boolean

In Python following are regarded as false and others are true. The representing value of true is True.

List of values regarded as false

Comparison operators are ==, !=, <, >, <=, >=, in, and is. The not toggles boolean values.
Appendex 2 summarizes comparison operators and functions that return booleans.

4.2. Loop

The while and for blocks are available for loop.

4.2.1. The while loop

The while block repeats evaluating the body_block while the test is true. The break and continue are available like the C language. If the while block terminates without breaking, the else_block is evaluated. The else_block can be omitted.
while test:
    body_block
    if break_test:
           break
    if continue_test:
           continue
else:
    else_block

4.2.2. The for loop

The for block evaluates body_block for each item (x) of the iterator. The break and continue are available like the while block. If the for block terminates without breaking, the else_block is evaluated. The else_block can be omitted.
for x in iterator:
    body_block
    if break_test:
           break
    if continue_test:
           continue
else:
    else_block

4.2.3. Tips for the for loop

Followings are some tips of the for loop.
range, xrange: loop in a range of number
The function range makes a list of numbers and returns it in an ordinal way. The for loop takes the list item one by one and applys the block to the number. On the other hand, the xrange is a generator and returns numbers in a lazy way (it returns a value only after the value being required). The xrange is suit for a wide range of numbers.
>>> for x in xrange(10):
	print x, ', ',

0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 
enumerate the iterator
The function enumerate is available for this.
>>> s='abc'
>>> for i, c in enumerate(s):
	print i, ':', c, ' ',

0 : a   1 : b   2 : c    
treating file contents line by line
The for loop takes file contents line by line if a file object is given as an iterator.
for line in _file:
     ..............
iteritems()
The iteritems() method of the dictionary returns a iterator object consisting of a tuple of the key and the value. As the dictionary is a hash table, the order of items are indeterminate.
>>> days = {'sun':0, 'mon':1, 'tue':2, 'wed':3, 'thu':4, 'fri':5, 'sat':6}
>>> for k, v in days.iteritems():
	print k, ':', v, ' ',

wed : 3   sun : 0   thu : 4   tue : 2   mon : 1   fri : 5   sat : 6  
zip()
This is a function to merge lists.
>>> zip(['Bill', 'Richard', 'Michael'], ['Lucia', 'Susan', 'Maria'])
[('Bill', 'Lucia'), ('Richard', 'Susan'), ('Michael', 'Maria')]

>>> questions = ['name', 'quest', 'favorite color']
>>> answers = ['lancelot', 'the holy grail', 'blue']
>>> for q, a in zip(questions, answers):
...     print 'What is your %s?  It is %s.' % (q, a)
... 
What is your name?  It is lancelot.
What is your quest?  It is the holy grail.
What is your favorite color?  It is blue.

4.2.4. List comprehensive

The list conprehensive is a sort of function that takes lists as arguments and that returns a list. The list comprehensive can perform filtering by if statement and multiple loops. The expression is similar to the mathematical one such as
X = {x | x is a positive integer}
This expression is quite useful. See Data types for more about list.
# calculating the square root if the list item is positive
ls = [1, 2, -3, -4]
# conventional loop
ls1=[]
for x in ls:
    if x > 0:
        ls1.append(math.sqrt(x))
return ls1

# list comprehensive
return [ math.sqrt(x) for x in ls if x > 0]
# making the multiplication table
# conventional loop
ls1=[]
for x in range(2,13):
    for y in range(2,13):
        ls1.append(x*y)
return ls1

# list conprehensive
return [x * y for x in range(2,13) for y in range(2,13)]

4.3. Exception handling

The try block is available for exception handling. The form of the try block is like as follows.
try:
    try_block
except ??Error:
    exept_block
else:
    else_block
finally:
    finally_block

  1. First, the try_block is executed.
  2. If a exception occurs, exept_block is executed.
    You can write several exept_blocks for distinct type of exceptions.
  3. If no exception occurs, the else_block is executed.
    You can omit this block.
  4. The finally_block block is always invoked regardless of exceptions.
    You can omit this.

When you create an instance of a class in which __enter__ and __exit__ methods are defined, The 'with' statement is also available.

See Tutorial 8. Errors and Exceptions for detailed information.

5. IO

See the library reference 2.3.9. for detailed information.

6. Defining functions

Functions are defined by statement def. You can use local variables without declaration. Use return statement to return value. If the first sentence of the function difinition is a string literal, the pydoc creates the document from the string automatically. Following code shows an example of function difinition. The function name follows the statement def. Then the list of parameters follows. After colon, newline and increasing indent, the body of the function difinition starts. Returning to the original indent terminates the function difinition.

See 7. Operators to know the function of the operators used in the following code.
See sections 4.6 and 4.7 of the tutorial for detailed information about defining functions.

def sum(ls):
    """ calculating the sum of the list items"""
    s=0
    for x in ls:
        s+=x
    return s
>>>sum([1,2,3])
6

6.1. Arguements

There are several ways to give arguments to a function.
def func(a, b, c): (ordinal way)
The function takes exact three arguments otherwise an error occurs. No default values are specified.
def func(a=0, b=1, c=2): (specifying default values)
The default values are used if the arguments are not given.
def func(a, *rest): (arbitrary number of arguments)
The rest is given as a tuple.
def func(**key): (parameters are given as adictionary
func(a=1, b=2) ⇒ key={'a':1, 'b':2} are given
If both *rest and **key are used, the *rest should be before the **key.

6.2. Generator

The generator returns values according to the internal state and returns different values each time when it is called. It is mainly used for the for loop.

The generator returns a value when it meets yield statement and halts calculating. When it is called again, the calculation starts again and halts at yield with returning a value.

A generator version of the range can be defined like as the following code.

import sys

def my_xrange(*parms):
    lp = len(parms)
    if not 0 <= lp <= 3:
        print >> sys.stderr, "Wrong argument count."

    if(lp==0):
        i = 0
        while True:
            yield i
            i += 1
    else:
        i, n, s = (lp==1 and (0, parms[0], 1)) or \
                  (lp==2 and (parms[0], parms[1], 1)) or \
                  (parms[0], parms[1], parms[2])

        if(s==0):
            print >> sys.stderr, "Step width shuld be non-zero."
        
        elif(s > 0):
            while(i < n):
                yield i
                i+=s
            
        else:
            while(i > n):
                yield i
                i+=s

7. Classes

I am explaining how to define classes using a vector class as an example. Operators '+' and '*' are overrode to calculate the sum and inner product.

Predefined data types can be a super class in Python 2.2 and later versions. A vector class using this feature is defined in The new class of Python. That difinition is more practical.

#! /usr/bin/env python

import sys, math

def sum(ls):
    """calculating the sum of the list items"""
    s=0
    for x in ls:
        s+=x
    return(s)

class Vector:
    """
    Vector is a class for vector operations.
    """
    def __init__(self, *rest, **key):
        """
        It initialize a vector.
        It makes a vector if the items are given like:
        v1 = Vector(1,2,3)
        If the dimension and the initial value is given, it makes a vector with dimension of dim with values val.
        The initial values are set to 0 if the val is omitted.
        v1 = Vector(dim=3, val=3)
        """
        if rest:
            self.v = list(rest)
        else:
            dim = key['dim']
            val = (('val' in key) and key['val']) or 0
            self.v =  [val for x in range(dim)]

    def __len__(self):
        """It returns the dimension of the vector."""
        return len(self.v)
    
    def abs(self):
        """It returns the absolute value of the vector."""
        return math.sqrt(sum([ x * x for x in self.v ]))

    def norm(self):
        """It returns the normalized vector."""
        a = self.abs()
        b = Vector(dim=len(self))
        b.v = [x/a for x in self.v]
        return b
        
    def __add__(self, a):
        """It calculates the sum of vector and number or vector and vector. """
        b = Vector(dim=len(self))
        if isinstance(a, Vector):
            if len(self) != len(a):
                print >> sys.stderr, "Dimension Error"
            else:
                b.v =  [ x + y for x, y in zip(self.v, a.v)]
        else:
            b.v = [ x + a for x in self.v]
        return b
            
    def __mul__(self, m):
        """It calculates the product of vector and number and the inner product of two vectors."""
        if isinstance(m, Vector):
            if len(self) != len(m):
                print >> sys.stderr, "Dimension Error"
            else:
                return sum([ x * y for x, y in zip(self.v, m.v)])
        else:
            b = Vector(dim=len(self))
            b.v = [ x * m for x in self.v]
            return b

    def __repr__(self):
        """It defines the string to print vectors."""
        return '#V' + `self.v`

    __str__ = __repr__

7.1. Defining classes

Defining classes can be done using following statement.
class class_name(*super_classes):
  .......
The parameters (*super_classes) are super classes to be inherited. Pyhton allows multiple inheritance.

7.2. Making instances

A special method __init__ is used to initialize instances. The first arguemnt (usually named self) of the method is the instance itself and the following arguments are paremeters to initialize the instance. In the case of the Vector class, instances are initialized like as follows:
# Giving vector items explicitly. 
>>>v1 = Vector(1,2,3)
# Giving dimension and initial value
>>>v2 = Vector(dim=3, val=0)

7.3. Defining methods

メソッドの定義は関数定義と同じ def を用います。 最初の仮引数はインスタンスそれ自身です。 ここでは、ベクトルの長さを返すメソッド abs と規格化されたベクトルを返す norm を定義しています。使うときはインスタンスの後ろに '.'(ドット)をつけてつなげます。
>>>v = Vector(1,2,3)
# 長さの計算
>>>v.abs()
3.7416573867739413

# 規格化する
>>>v.norm()
#V[0.2672612419124244, 0.53452248382484879, 0.80178372573727319]

7.4. 関数や演算子のオーバーライド

既存の関数を再定義することが出来ます。 __add__ は足し算を、__mul__ は掛け算を定義します。 また、__repr__ は表示方法を定義します。 他にもいろいろあります。詳しくは リファレンスマニュアル 3.3 を参照してください。 使い方は以下の通りです。
>>> v1=Vector(1,2,3)
>>> v2=Vector(dim=3, val=2)
>>> v1+10
#V[11, 12, 13]
>>> v1+v2
#V[3, 4, 5]
>>> v1*100
#V[100, 200, 300]
>>> v1*v2
12

7.6. 関数のクラス

__call__ メソッド のあるクラスは関数のクラスとして機能します。 詳しくは、 リファレンスマニュアル 3.3.4. を見てください。

7.6. イテレーター

イテレータークラスを定義することも出来ます。 通常は generator を使ったほうが楽でしょう。 詳しくは チュートリアル 9.8. を見てください。

8. データ型

8.1. 数値

数値型には、整数型 、 長整数型 、浮動小数点型 、および 複素数型 の4つの型があります。 詳しくは
ライブラリリファレンス 2.3.4 を見てください。

8.2. 配列

配列型には、文字列、ユニコード文字列、リスト、タプル、バッファ、そして xrange オブジェクトの 6つがあります。配列型に共通の演算を下の表にまとめます。
演算  結果 
x in s s のある要素 x と等しい場合 True 、そうでない場合 False
s + t s および t の結合
s * n , n * s s の浅いコピー n 個からなる結合
s[i] s の 0 から数えて i 番目の要素
s[i:j] si 番目から j 番目までのスライス
s[i:j:k] si 番目から j 番目まで、k 毎のスライス
len(s) s の長さ
min(s) s の最小の要素
max(s) s の最大の要素
# 例
>>> s='abcde'
>>> s[-1]      # インデックス -1 は最後の要素
'e'
>>> s[1:]      # 最初の要素を除く
'bcde'
>>> s[:-1]     # 最後の要素を除く
'abcd'
>>> s*2
'abcdeabcde'
>>> min(s)
'a'
>>> max(s)
'e'
>>> s[0:-1:2]
'ac'

8.2.1. 文字列、ユニコード文字列

文字列の要素に直接値を代入することは出来ません。
s = 'abcdefg'
# 不可、文字を直接代入できない。
s[0]='z'

# 次のようにして全体を作り直す必要がある。
s = 'z' + s[1:]

文字列リテラル

文字列リテラルについての詳細は
リファレンスマニュアル 2.4.1 を見てください。

文字列メソッド

ライブラリリファレンス 2.3.6.1 を見てください。

Memo:
文字列 line から末尾の改行文字を取り除くには、

line = line.rstrip('\n')
# あるいは、
import string
line = string.rstrip(line, '\n')
とします。ファイルから1行ずつ読み込むときよく使います。

文字列フォーマット

format % vars というように記述します。 format は C 言語風です。 vars が複数の場合 ( ) で くくる必要があります。 また、vars辞書型 を指定してキーワードで指定することも出来ます。 詳しくは ライブラリリファレンス 2.3.6.2 文字列フォーマット操作を見てください。
>>>'%d:%d' % (1, 2)
'1:2'
>>>'%(month)s %(date)d, %(year)4d' % {'year':2005, 'month':'February', 'date':3}
'February 3, 2005'

8.2.2. リスト

リストは [ ] でくくってあらわします。リストの各要素に直接値を代入できます。 また、リストはネストできます。
>>> ls=[1,2,3]
>>> ls[0]=100
>>> ls
[100, 2, 3]
>>> ls2=[ls, 10,20,30]
>>> ls2
[[100, 2, 3], 10, 20, 30]
リストの操作については ライブラリリファレンス 2.3.6.4 を見てください。

Memo:
リストの末尾に要素を1つくわえるには append を使います。

>>>ls = []
>>>ls.append(1)
>>>ls
[1]

8.2.3. タプル

タプルは (,) を使ってあらわします。変更できない点を除いてリストと同じです。 リストより高速です。変更するつもりがない値のセットはタプルとして定義すると良いでしょう。
なお、項が1つのタプルは項の後にカンマをつけて (item,) と書きます。

詳しくは チュートリアル 5.3. を見てください。

8.3. 辞書型

いわゆるハッシュ表です。数値、文字列、タプルを key として、対応する値を保持したり、取り出したりすることが出来ます。 初期化は、全体を { } でくくって、コロン ':' で対になった key:val のペアをコンマで区切ります。 代入や、削除が出来ます。 ある key が辞書に登録されているかは in を使って調べられます。
注意:リストは辞書型の key になれません。
例:
>>>days = {'sun':0, 'mon':1, 'tue':2, 'wed':3, 'thu':4, 'fri':5, 'sat':6}  # 初期化
>>>'sun' in days                                                           # 存在するか?
True
>>>month={}
>>>month['jan'] = 1                                                        # 代入
>>>month['jan'] += 1
>>>month['jan']
2
>>>del month['jan']                                                        # 削除
詳しくは
ライブラリリファレンス 2.3.7. を見てください。

9. 演算子

注意: Python の例で、値をタプルでくくっているのは、 Python の場合、test が真でも、then_value が偽と認識される値(0, '' など)のときは else_value が返ってきてしまうからです。 もし、then_value が絶対に偽にならないときはタプルをはずして次のように書くこともできます。 しかし、紫藤はタプルつきの方をお勧めします。
a = test and then_value or else_value
詳しくは、リファレンスマニュアル 2.5, 2.6 を見てください。

10. ライブラリーツアー

よく使うライブラリーを簡単に説明します。 詳しくは
ライブラリーリファレンスを見てください。

10.1. sys

sys.argv
コマンドラインから渡された引数のリストです。 sys.argv[0] はスクリプト自身で、実際の引数は sys.argv[1:] です。
sys.exit()
Python を終了するとき使います。
詳しくは ライブラリリファレンス 3.1 を見てください。

10.2. os

以下は抜粋。詳しくは ライブラリリファレンス 6.1 を見てください。
chdir(path)
現在の作業ディレクトリを path に設定します。
getcwd()
現在の作業ディレクトリを表現する文字列を返します。
listdir(path)
ディレクトリ内のエントリ名が入ったリストを返します。リスト内の順番は不定です。特殊エントリ '.' および '..' は、それらがディレクトリに入っていてもリストには含められません。
mkdir(path[, mode])
数値で指定されたモード mode をもつディレクトリ path を作成します。
remove(path)
ファイル path を削除します。
rename(src, dst)
ファイルまたはディレクトリ srcdst に名前変更します。
exec[l, le, lp, lpe, v, ve, vp, vpe]
外部プロセスを起動します。

10.3. os.path

exists, getatime, getmtime, getsize, isfile, isdir などの関数を含むモジュールです。 詳しくは ライブラリリファレンス 6.2. を見てください。

10.4. fileinput

Perl の "while(<>)" のように、コマンドラインの引数で与えられたファイルから入力します。
# fileinput を使わないと
for fname in sys.argv[1:]:
    f=file(fname)
    for line in f:
        (do something with line)
    f.close()

# fileinput を使うと
import fileinput
for line in fileinput.input():
    (do something with line)
詳しくは ライブラリリファレンス 5.15 を見てください。

10.5. re

正規表現のモジュールです。
  1. Python では、パターンをまず compile して、正規表現オブジェクトを 作ってから検索します。
  2. パターンは raw_string を使って書くのが便利です。
  3. 正規表現オブジェクトは match, finditer, split などのメソッドを持ちます。 詳しくは ライブラリリファレンス 4.2.4 を見てください。
  4. 正規表現オブジェクトで文字列を検索してマッチした部分文字列は、 マッチオブジェクトとして返されます。
  5. マッチオブジェクトから文字列を取り出したいときは group メソッドを使います。 また、start, end メソッドで マッチした部分文字列の位置を取り出せます。
詳しくは ライブラリリファレンス 4.2.5 を見てください。

例、HTML ファイルからリンクを取り出す。

#! /usr/bin/env python
# coding: shift_jis

"""
引数で与えられたファイルを検索してリンクをを探し、
それを rink.txt に書き出す。
"""

import sys

RINK = 'rink.txt'
A_HREF = re.compile("<a href ?= ?\"http://([^\"]+)\">([^<]+)</a>", re.S) 

#main
if __name__=='__main__':
    rink_hash={}
    for fname in sys.argv[1:]:
        f=file(fname, 'r')
        for m in A_HREF.finditer(f.read()):
            rink_hash[m.group(1)] = m.group(2)
        f.close()
    fout = file(RINK, 'w')
    for address, name in rink_hash.iteritems():
        fout.write("<li> <a href = \"http://%s\">%s</a>\n" % (address, name))
    fout.close()

10.6. shutil, filecmp, glob

shutil.copyfile
ファイルをコピーします。
filecmp.cmp
ファイルの比較をします。
glob.glob(pattern)
現在のディレクトリのエントリーのうち pattern のマッチするものを返します。
詳しくは、ライブラリリファレンス 6.7, 6.23, 6.25 を見てください。

10.7. datetime

日時を得るのに使います。 datetime time とほぼ同様ですが、time が 1970--2038 年しか扱えないのに対し、 datetime は それ以前もそれ以降も取り扱えます。
datetime.date.today()
現在のローカルな日付を得ます。
datetime.datetime.now()
現在のローカルな日付と時刻を得ます。
isoformat メソッド
日付と時刻を ISO 8601 形式の文字列にします。
>>> datetime.date.today().isoformat()
'2005-02-02'
>>> datetime.datetime.now().isoformat()
'2005-02-02T17:50:09.867000'
strftime
日時を書式に従って出力します。詳しくはライブラリリファレンス 6.9.7, 6.10 を見てください。
>>> datetime.datetime.now().strftime('%y-%m-%d: %H:%M:%S')
'05-02-02: 23:20:12'
>>> datetime.date.today().strftime('%y-%m-%d')
'05-02-02'

10.8. operator

add(a,b) (通常の書式では `a+b') や mul(a,b) (通常の書式では `a*b') を定義したモジュール。 reduce を使うとき便利。
>>> import operator as op
>>> reduce(op.add, [1,2,3,4,5])  # 1+2+3+4+5
15
詳しくは、 ライブラリリファレンス 3.10. operator -- 関数形式の標準演算子を見てください。

10.9. その他のモジュール

  1. 各種サービス
  2. 汎用オペレーティングシステムサービス
  3. オプションのオペレーティングシステムサービス
  4. Unix独特のサービス
  5. インターネットプロトコルとその支援

11. 付録

11.1. 真偽値を返す演算子と主な関数

モジュール 演算子、関数 機能 (True でない場合は False)
組み込み == 左辺と右辺が等しければ True。
組み込み != 左辺と右辺が等しくなければ True。
組み込み < 左辺が右辺より小さければ True。
文字列にも使える。例: 'abc' < 'ab' &rArr False
組み込み > 左辺が右辺より大きければ True。 文字列にも使える。
組み込み <= 左辺が右辺より小さいか、左辺と右辺が等しければ True。 文字列にも使える。
組み込み >= 左辺が右辺より大きいか、左辺と右辺が等しければ True。 文字列にも使える。
組み込み in 左辺が右辺に含まれていれば True。 例:
リスト: 1 in [1,2,3] &rArr True
文字列: 'ab' in 'abc' &rArr True
辞書: 'mon' in {'sun':0, 'mon':1, 'tue':2, 'wed':3} &rArr True
組み込み is 左辺と右辺が等しオブジェクトならば True。
ls1 = [1,2,3]
ls2 = [1,2,3]
ls3 = ls1
ls1 is ls2 &rArr False
ls1 is ls3 &rArr True
組み込み isinstance( object, classinfo) 引数 object が引数 classinfo のインスタンスであるか、 (直接または間接的な) サブクラスのインスタンスの場合 True。
組み込み issubclass( class, classinfo) class が classinfo の (直接または間接的な) サブクラスである場合に True。
文字列メソッド isalnum() 文字列中の全ての文字が英数文字 [a-zA-Z0-9] で、かつ 1 文字以上ある場合 True。
文字列メソッド isalpha() 文字列中の全ての文字が英文字 [a-zA-Z] で、かつ 1 文字以上ある場合 True。
文字列メソッド isdigit() 文字列中に数字しかない場合 True。
文字列メソッド islower() 文字列中の大小文字の区別のある文字全てが小文字で、かつ 1 文字以上ある場合 True。
文字列メソッド isspace() 文字列が空白文字だけからなり、かつ 1 文字以上ある場合 True。
文字列メソッド istitle() 文字列がタイトルケース文字列であり、かつ 1 文字以上ある場合、 すなわち大文字は大小文字の区別のない文字の後にのみ続き、 小文字は大小文字の区別のある文字の後ろにのみ続く場合 True。
文字列メソッド isupper() 文字列中の大小文字の区別のある文字全てが大文字で、かつ 1 文字以上ある場合 True。
os.path exists(path) path が存在する場合 True。
os.path isfile(path) path が存在する正しいファイルの場合 True。
os.path isdir(path) path がディレクトリの場合 True。
fileinput isfirstline() 最後に読み込まれた行がファイルの1行目なら True。
fileinput isstdin() 最後に読み込まれた行がsys.stdinから読まれていれば True。

11.2. web documents

  1. python.org
    1. ダウンロード
    2. ドキュメント
  2. 日本Pythonユーザ会
    1. 日本語訳ドキュメント
    2. 小さな実例集
    3. リンク集
  3. Dive Into Python: この文書と チュートリアルの次に 読む文書としてお勧めです。