![]() |
![]() |
![]() |
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.
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. |
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.'
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
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
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))
if test: then_block elif test_elif: elif_block else: else_blockFirst 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.
List of values regarded as false
while test: body_block if break_test: break if continue_test: continue else: else_block
for x in iterator: body_block if break_test: break if continue_test: continue else: else_block
>>> for x in xrange(10): print x, ', ', 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
>>> s='abc' >>> for i, c in enumerate(s): print i, ':', c, ' ', 0 : a 1 : b 2 : c
for line in _file:
..............
>>> 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(['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.
# 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)]
try: try_block except ??Error: exept_block else: else_block finally: finally_block
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.
See 7. Operators to know the function of the operators used in the following code.
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.
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.
Memo:
Memo:
詳しくは
チュートリアル 5.3. を見てください。
例、HTML ファイルからリンクを取り出す。
5. IO
5.1. The print statement
The print statement is used to output values. A linefeed is inserted at the end.
Data are conveted to corresponding string to output.
Following shows the form.
If the file handle (file_handle) is specified, values are output to the file handle.
otherwise they are output to the standard output.
print >> file_handle, value1, value2, ....
5.2. File handle
f = file('file_name', mode)
The file mode (mode) is almost the same as that of the C language.
Descriptors 'r', 'w', 'a', and 'b' represent reading, writing, adding, and binary, respectively.
Reading and writing in the binary mode are represented by 'rb' and 'wb'.
f.read(n)
If n is omitted, all contents of the file are read.
s = f.readline()
The linefeed is included at the end.
To remove the linefeed, do
s[:-1] or s.rstrip('\n').
f.close()
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 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.
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.
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.
#! /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]
s の i 番目から j 番目までのスライス
s[i:j:k]
s の i 番目から 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 を見てください。
文字列 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 を見てください。
リストの末尾に要素を1つくわえるには append を使います。
>>>ls = []
>>>ls.append(1)
>>>ls
[1]
8.2.3. タプル
タプルは (,) を使ってあらわします。変更できない点を除いてリストと同じです。
リストより高速です。変更するつもりがない値のセットはタプルとして定義すると良いでしょう。
なお、項が1つのタプルは項の後にカンマをつけて (item,) と書きます。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 が絶対に偽にならないときはタプルをはずして次のように書くこともできます。
しかし、紫藤はタプルつきの方をお勧めします。
and と or を組み合わせると C 言語の三項演算子または Lisp の if に相当するものが書けます。
# C
a = test? then_value: else_value
# Lisp
(setf a (if test then_value else_value))
# Python
(a,) = test and (then_value,) or (else_value,)
a = test and then_value or else_value
詳しくは、リファレンスマニュアル
2.5,
2.6 を見てください。
10. ライブラリーツアー
よく使うライブラリーを簡単に説明します。
詳しくは
ライブラリーリファレンスを見てください。
10.1. sys
詳しくは
ライブラリリファレンス 3.1 を見てください。
10.2. os
以下は抜粋。詳しくは
ライブラリリファレンス 6.1 を見てください。
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
正規表現のモジュールです。
詳しくは
ライブラリリファレンス 4.2.5 を見てください。
#! /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
詳しくは、ライブラリリファレンス
6.7,
6.23,
6.25 を見てください。
10.7. datetime
日時を得るのに使います。
datetime は
time とほぼ同様ですが、time が 1970--2038 年しか扱えないのに対し、
datetime は それ以前もそれ以降も取り扱えます。
>>> datetime.date.today().isoformat()
'2005-02-02'
>>> datetime.datetime.now().isoformat()
'2005-02-02T17:50:09.867000'
>>> 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. その他のモジュール
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
HOME
Python
Post Messages