形式ばらない Python の紹介
**************************

以下の例では、入力と出力は (*>>>* や *…*) といったプロンプトの有無で区
別します: 例を実際に試してみるためには、プロンプトが表示されているとき
に、例中のプロンプトから後ろの内容全てを入力しなければなりません; プロ
ンプトが先頭にない行はインタプリタからの出力です。例中には2つ目のプロ
ンプトだけが表示されている行がありますが、これは空行を入力しなければな
らないことを意味しています; 空行の入力は複数の行からなる命令の終わりを
インタプリタに教えるために使われます。

このマニュアルにある例の多くは、対話プロンプトで入力されるものでもコメ
ントを含んでいます。 Python におけるコメント文はハッシュ文字 "#" で始
まり、物理行の終わりまで続きます。コメントは行の先頭にも、空白やコード
の後にも書くことができますが、文字列リテラルの内部に置くことはできませ
ん。文字列リテラル中のハッシュ文字はただのハッシュ文字です。コメントは
コードを明快にするためのものであり、Pythonはコメントを解釈しません。な
ので、コードサンプルを実際に入力して試して見るときは、コメントをを省い
ても大丈夫です。

いくつかの例です:

   # this is the first comment
   spam = 1  # and this is the second comment
             # ... and now a third!
   text = "# This is not a comment because it's inside quotes."


Python を電卓として使う
=======================

それでは、簡単な Python コマンドをいくつか試しましょう。インタプリタを
起動して、一次プロンプト、 ">>>" が現れるのを待ちます。 (そう長くはか
からないはずです)


数
--

インタプリタは単純な電卓のように動作します: 式を入力すると、その結果が
表示されます。式の文法は素直なものです: 演算子 "+", "-", "*", "/"  は
(Pascal や C といった) 他のほとんどの言語と同じように動作します; 丸括
弧 ("()") をグループ化に使うこともできます。例えば:

   >>> 2 + 2
   4
   >>> 50 - 5*6
   20
   >>> (50 - 5.0*6) / 4
   5.0
   >>> 8 / 5.0
   1.6

整数 (例えば、 "2" 、 "4" 、 "20") は "int" 型を持ち、小数部を持つ数 (
例えば、 "5.0" 、 "1.6") は "float" 型を持ちます。数値型については後の
チュートリアルでさらに見ていきます。

The return type of a division ("/") operation depends on its operands.
If both operands are of type "int", *floor division* is performed and
an "int" is returned.  If either operand is a "float", classic
division is performed and a "float" is returned.  The "//" operator is
also provided for doing floor division no matter what the operands
are.  The remainder can be calculated with the "%" operator:

   >>> 17 / 3  # int / int -> int
   5
   >>> 17 / 3.0  # int / float -> float
   5.666666666666667
   >>> 17 // 3.0  # explicit floor division discards the fractional part
   5.0
   >>> 17 % 3  # the % operator returns the remainder of the division
   2
   >>> 5 * 3 + 2  # result * divisor + remainder
   17

Python では、冪乗を計算するのに "**" 演算子が使えます [1]:

   >>> 5 ** 2  # 5 squared
   25
   >>> 2 ** 7  # 2 to the power of 7
   128

等号 ("=") は変数に値を代入するときに使います。代入を行っても、次のプ
ロンプトの手前には結果は出力されません:

   >>> width = 20
   >>> height = 5 * 9
   >>> width * height
   900

変数が 「定義」 されて (つまり値が代入されて) いない場合、その変数を使
おうとするとエラーが発生します:

   >>> n  # try to access an undefined variable
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   NameError: name 'n' is not defined

浮動小数点を完全にサポートしています。演算対象の値(オペランド)の型が統
一されていない場合、演算子は整数のオペランドを浮動小数点型に変換します
:

   >>> 3 * 3.75 / 1.5
   7.5
   >>> 7.0 / 2
   3.5

対話モードでは、最後に表示された結果は変数 "_" に代入されます。このこ
とを利用すると、Python を電卓として使うときに、計算を連続して行う作業
が多少楽になります。以下に例を示します:

   >>> tax = 12.5 / 100
   >>> price = 100.50
   >>> price * tax
   12.5625
   >>> price + _
   113.0625
   >>> round(_, 2)
   113.06

ユーザはこの変数を読取り専用の値として扱うべきです。この変数に明示的な
代入を行ってはいけません — そんなことをすれば、同じ名前で元の特別な動
作をする組み込み変数を覆い隠してしまうような、別のローカルな変数が生成
されてしまいます。

"int" と "float" に加え、 Python は "Decimal" や "Fraction" のような他
の数値型をサポートしています。 Python はビルトインで 複素数 もサポート
し、 "j" もしくは "J" 接尾辞を使って虚部を示します (例。 "3+5j")。


文字列型 (string)
-----------------

数のほかに、Python は文字列の操作ができ、文字列はいくつもの方法で表現
できます。文字列は単引用符 ("'...'") もしくは二重引用符 (""..."") で囲
み、結果はどちらも同じ文字列になります。[2] "\" は引用符をエスケープす
るのに使います:

   >>> 'spam eggs'  # single quotes
   'spam eggs'
   >>> 'doesn\'t'  # use \' to escape the single quote...
   "doesn't"
   >>> "doesn't"  # ...or use double quotes instead
   "doesn't"
   >>> '"Yes," he said.'
   '"Yes," he said.'
   >>> "\"Yes,\" he said."
   '"Yes," he said.'
   >>> '"Isn\'t," she said.'
   '"Isn\'t," she said.'

In the interactive interpreter, the output string is enclosed in
quotes and special characters are escaped with backslashes.  While
this might sometimes look different from the input (the enclosing
quotes could change), the two strings are equivalent.  The string is
enclosed in double quotes if the string contains a single quote and no
double quotes, otherwise it is enclosed in single quotes.  The "print"
statement produces a more readable output, by omitting the enclosing
quotes and by printing escaped and special characters:

   >>> '"Isn\'t," she said.'
   '"Isn\'t," she said.'
   >>> print '"Isn\'t," she said.'
   "Isn't," she said.
   >>> s = 'First line.\nSecond line.'  # \n means newline
   >>> s  # without print, \n is included in the output
   'First line.\nSecond line.'
   >>> print s  # with print, \n produces a new line
   First line.
   Second line.

特殊文字として解釈させるために文字の前に "\" を付けることをしたくない
場合は、最初の引用符の前に "r" を付けた *raw strings* が使えます:

   >>> print 'C:\some\name'  # here \n means newline!
   C:\some
   ame
   >>> print r'C:\some\name'  # note the r before the quote
   C:\some\name

文字列リテラルは複数行にまたがって書けます。1 つの方法は三連引用符
(""""..."""" や "'''...'''") を使うことです。行末は自動的に文字列に含
まれますが、行末に "\" を付けることで含めないようにすることもできます
。次の例:

   print """\
   Usage: thingy [OPTIONS]
        -h                        Display this usage message
        -H hostname               Hostname to connect to
   """

は次のような出力になります (最初の改行文字は含まれていないことに注意し
てください):

   Usage: thingy [OPTIONS]
        -h                        Display this usage message
        -H hostname               Hostname to connect to

文字列は "+" 演算子で連結させる (くっつけて一つにする) ことができ、"*"
演算子で反復させることができます:

   >>> # 3 times 'un', followed by 'ium'
   >>> 3 * 'un' + 'ium'
   'unununium'

連続して並んでいる複数の *文字列リテラル* (つまり、引用符に囲われた文
字列) は自動的に連結されます。

   >>> 'Py' 'thon'
   'Python'

この機能は特に、長い文字列を改行したいときに役に立ちます:

   >>> text = ('Put several strings within parentheses '
   ...         'to have them joined together.')
   >>> text
   'Put several strings within parentheses to have them joined together.'

これは 2 つのリテラルどうしに対してのみ働き、変数や式には働きません:

   >>> prefix = 'Py'
   >>> prefix 'thon'  # can't concatenate a variable and a string literal
     ...
   SyntaxError: invalid syntax
   >>> ('un' * 3) 'ium'
     ...
   SyntaxError: invalid syntax

変数どうしや変数とリテラルを連結したい場合は、"+" を使ってください:

   >>> prefix + 'thon'
   'Python'

文字列は *インデクス表記* (添字表記) することができ、最初の文字のイン
デクスは 0 になります。文字列型と区別された文字型はありません; 文字と
いうのは単なる長さが 1 の文字列です:

   >>> word = 'Python'
   >>> word[0]  # character in position 0
   'P'
   >>> word[5]  # character in position 5
   'n'

インデクスは負の数を指定しても良く、そのときは右から数えていきます:

   >>> word[-1]  # last character
   'n'
   >>> word[-2]  # second-last character
   'o'
   >>> word[-6]
   'P'

-0 は 0 と等しいので、負のインデクスは -1 から始まることに注意してくだ
さい。

In addition to indexing, *slicing* is also supported.  While indexing
is used to obtain individual characters, *slicing* allows you to
obtain a substring:

   >>> word[0:2]  # characters from position 0 (included) to 2 (excluded)
   'Py'
   >>> word[2:5]  # characters from position 2 (included) to 5 (excluded)
   'tho'

開始インデクスは常に含まれ、終了インデクスは常に含まれないことに注意し
てください。なので "s[:i] + s[i:]" が常に "s" と等しい、ということにな
ります:

   >>> word[:2] + word[2:]
   'Python'
   >>> word[:4] + word[4:]
   'Python'

スライスのインデクスには便利なデフォルト値があります; 最初のインデクス
を省略すると、0 と見なされます。第 2 のインデクスを省略すると、スライ
スしようとする文字列のサイズとみなされます。

   >>> word[:2]   # character from the beginning to position 2 (excluded)
   'Py'
   >>> word[4:]   # characters from position 4 (included) to the end
   'on'
   >>> word[-2:]  # characters from the second-last (included) to the end
   'on'

スライスの働きかたをおぼえる良い方法は、インデクスが文字と文字の *あい
だ (between)* を指しており、最初の文字の左端が 0 になっていると考える
ことです。そうすると、 *n* 文字からなる文字列中の最後の文字の右端はイ
ンデクス *n* となります。例えばこうです:

    +---+---+---+---+---+---+
    | P | y | t | h | o | n |
    +---+---+---+---+---+---+
    0   1   2   3   4   5   6
   -6  -5  -4  -3  -2  -1

1行目の数字は文字列の 0 から 6 までのインデクスの位置を示しています; 2
行目は対応する負のインデクスを示しています。*i* から *j* までのスライ
スは、それぞれ *i* と付いた境界から *j* と付いた境界までの全ての文字か
ら成っています。

非負のインデクス対の場合、スライスされたシーケンスの長さは、スライスの
両端のインデクスが範囲内にあるかぎり、インデクス間の差になります。例え
ば、 "word[1:3]" の長さは 2 になります。

大き過ぎるインデクスを使おうとするとエラーが発生します:

   >>> word[42]  # the word only has 6 characters
   Traceback (most recent call last):
     File "<stdin>", line 1, in <module>
   IndexError: string index out of range

しかし、スライスで範囲外のインデクスを使ったときは上手く対応して扱って
くれます:

   >>> word[4:42]
   'on'
   >>> word[42:]
   ''

Python の文字列は変更できません – つまり不変 (*immutable*) なのです。
従って、文字列のインデクスで指定したある場所に代入を行うとエラーが発生
します:

   >>> word[0] = 'J'
     ...
   TypeError: 'str' object does not support item assignment
   >>> word[2:] = 'py'
     ...
   TypeError: 'str' object does not support item assignment

元の文字列と別の文字列が必要な場合は、新しく文字列を作成してください:

   >>> 'J' + word[1:]
   'Jython'
   >>> word[:2] + 'py'
   'Pypy'

組込み関数 "len()" は文字列の長さ (length) を返します:

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

参考:

  Sequence Types — str, unicode, list, tuple, bytearray, buffer,
  xrange
     Strings, and the Unicode strings described in the next section,
     are examples of *sequence types*, and support the common
     operations supported by such types.

  文字列メソッド
     Both strings and Unicode strings support a large number of
     methods for basic transformations and searching.

  書式指定文字列の文法
     "str.format()" を使った文字列のフォーマットについての情報がありま
     す。

  String Formatting Operations
     The old formatting operations invoked when strings and Unicode
     strings are the left operand of the "%" operator are described in
     more detail here.


Unicode Strings
---------------

Starting with Python 2.0 a new data type for storing text data is
available to the programmer: the Unicode object. It can be used to
store and manipulate Unicode data (see http://www.unicode.org/) and
integrates well with the existing string objects, providing auto-
conversions where necessary.

Unicode has the advantage of providing one ordinal for every character
in every script used in modern and ancient texts. Previously, there
were only 256 possible ordinals for script characters. Texts were
typically bound to a code page which mapped the ordinals to script
characters. This lead to very much confusion especially with respect
to internationalization (usually written as "i18n" — "'i'" + 18
characters + "'n'") of software.  Unicode solves these problems by
defining one code page for all scripts.

Creating Unicode strings in Python is just as simple as creating
normal strings:

   >>> u'Hello World !'
   u'Hello World !'

The small "'u'" in front of the quote indicates that a Unicode string
is supposed to be created. If you want to include special characters
in the string, you can do so by using the Python *Unicode-Escape*
encoding. The following example shows how:

   >>> u'Hello\u0020World !'
   u'Hello World !'

The escape sequence "\u0020" indicates to insert the Unicode character
with the ordinal value 0x0020 (the space character) at the given
position.

Other characters are interpreted by using their respective ordinal
values directly as Unicode ordinals.  If you have literal strings in
the standard Latin-1 encoding that is used in many Western countries,
you will find it convenient that the lower 256 characters of Unicode
are the same as the 256 characters of Latin-1.

For experts, there is also a raw mode just like the one for normal
strings. You have to prefix the opening quote with 『ur』 to have
Python use the *Raw-Unicode-Escape* encoding. It will only apply the
above "\uXXXX" conversion if there is an uneven number of backslashes
in front of the small 『u』.

   >>> ur'Hello\u0020World !'
   u'Hello World !'
   >>> ur'Hello\\u0020World !'
   u'Hello\\\\u0020World !'

The raw mode is most useful when you have to enter lots of
backslashes, as can be necessary in regular expressions.

Apart from these standard encodings, Python provides a whole set of
other ways of creating Unicode strings on the basis of a known
encoding.

The built-in function "unicode()" provides access to all registered
Unicode codecs (COders and DECoders). Some of the more well known
encodings which these codecs can convert are *Latin-1*, *ASCII*,
*UTF-8*, and *UTF-16*. The latter two are variable-length encodings
that store each Unicode character in one or more bytes. The default
encoding is normally set to ASCII, which passes through characters in
the range 0 to 127 and rejects any other characters with an error.
When a Unicode string is printed, written to a file, or converted with
"str()", conversion takes place using this default encoding.

   >>> u"abc"
   u'abc'
   >>> str(u"abc")
   'abc'
   >>> u"äöü"
   u'\xe4\xf6\xfc'
   >>> str(u"äöü")
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)

To convert a Unicode string into an 8-bit string using a specific
encoding, Unicode objects provide an "encode()" method that takes one
argument, the name of the encoding.  Lowercase names for encodings are
preferred.

   >>> u"äöü".encode('utf-8')
   '\xc3\xa4\xc3\xb6\xc3\xbc'

If you have data in a specific encoding and want to produce a
corresponding Unicode string from it, you can use the "unicode()"
function with the encoding name as the second argument.

   >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
   u'\xe4\xf6\xfc'


リスト型 (list)
---------------

Python 多くの *複合 (compound)* データ型を備えており、複数の値をまとめ
るのに使われます。最も汎用性が高いのは *リスト (list)* で、コンマ区切
りの値 (要素) の並びを角括弧で囲んだものとして書き表されます。リストは
異なる型の要素を含むこともありますが、通常は全ての要素は同じ型を持ちま
す。

   >>> squares = [1, 4, 9, 16, 25]
   >>> squares
   [1, 4, 9, 16, 25]

文字列 (や他の全てのビルトインのシーケンス (*sequence*) 型) のように、
リストはインデクス表記やスライス表記ができます:

   >>> squares[0]  # indexing returns the item
   1
   >>> squares[-1]
   25
   >>> squares[-3:]  # slicing returns a new list
   [9, 16, 25]

全てのスライス操作は指定された要素を含む新しいリストを返します。これは
、次のスライスはリストの新しい (浅い) コピーを返すことを意味します:

   >>> squares[:]
   [1, 4, 9, 16, 25]

Lists also supports operations like concatenation:

   >>> squares + [36, 49, 64, 81, 100]
   [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

不変 (*immutable*) な文字列とは違って、リストは可変 (*mutable*) 型、つ
まり含んでいる要素を取り替えることができます:

   >>> cubes = [1, 8, 27, 65, 125]  # something's wrong here
   >>> 4 ** 3  # the cube of 4 is 64, not 65!
   64
   >>> cubes[3] = 64  # replace the wrong value
   >>> cubes
   [1, 8, 27, 64, 125]

"append()" を使って、リストの末尾に新しい要素を追加することもできます
(このメソッドについては後で詳しく見ていきます):

   >>> cubes.append(216)  # add the cube of 6
   >>> cubes.append(7 ** 3)  # and the cube of 7
   >>> cubes
   [1, 8, 27, 64, 125, 216, 343]

スライスに代入することもできます。スライスの代入を行って、リストのサイ
ズを変更したり、完全に消すことさえできます:

   >>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
   >>> letters
   ['a', 'b', 'c', 'd', 'e', 'f', 'g']
   >>> # replace some values
   >>> letters[2:5] = ['C', 'D', 'E']
   >>> letters
   ['a', 'b', 'C', 'D', 'E', 'f', 'g']
   >>> # now remove them
   >>> letters[2:5] = []
   >>> letters
   ['a', 'b', 'f', 'g']
   >>> # clear the list by replacing all the elements with an empty list
   >>> letters[:] = []
   >>> letters
   []

組込み関数 "len()" はリストにも適用できます:

   >>> letters = ['a', 'b', 'c', 'd']
   >>> len(letters)
   4

リストを入れ子にする (ほかのリストを含むリストを造る) ことも可能です。
例えば:

   >>> a = ['a', 'b', 'c']
   >>> n = [1, 2, 3]
   >>> x = [a, n]
   >>> x
   [['a', 'b', 'c'], [1, 2, 3]]
   >>> x[0]
   ['a', 'b', 'c']
   >>> x[0][1]
   'b'


プログラミングへの第一歩
========================

もちろん、2 たす 2 よりももっと複雑な仕事にも Python を使うことができ
ます。*Fibonacci* 級数列の先頭の部分列は次のようにして書くことができま
す:

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

上の例では、いくつか新しい機能を取り入れています。

* 最初の行には *複数同時の代入 (multiple assignment)* が入っています
  : 変数 "a" と "b" は、それぞれ同時に新しい値 0 と 1 になっています。
  こ の代入は最後の行でも再度使われており、代入が行われる前に右辺の式
  がま ず評価されます。右辺の式は左から右へと順番に評価されます。

* "while" は、条件 (ここでは "b < 10") が真である限り実行を繰り返し
  ( ループし) ます。Python では、C 言語と同様に、ゼロでない整数値は真
  と なり、ゼロは偽です。条件式は文字列値やリスト値、実際には任意のシ
  ーケ ンス型でもかまいません。 1つ以上の長さのシーケンスは真で、空の
  シーケ ンスは偽になります。例中で使われている条件テストはシンプルな
  比較です 。標準的な比較演算子は C 言語と同様です: すなわち、 "<" (よ
  り小さい) 、 ">" (より大きい)、 "==" (等しい)、 "<=" (より小さいか等
  しい)、 ">=" (より大きいか等しい)、および "!=" (等しくない)、です。

* ループの *本体 (body)* は *インデント (indent, 字下げ)*  されてい
  ま す: インデントは Python において実行文をグループにまとめる方法で
  す。 対話的プロンプトでは、インデントされた各行を入力するにはタブや
  (複数 個の) スペースを使わなければなりません。実際には、Python への
  より複 雑な入力を準備するにはテキストエディタを使うことになるでしょ
  う; ほと んどのテキストエディタは自動インデント機能を持っています。
  複合文を対 話的に入力するときには、(パーザはいつ最後の行を入力したの
  か推し量る ことができないので) 入力の完了を示すために最後に空行を続
  けなければな りません。基本ブロックの各行は同じだけインデントされて
  いなければなら ないので注意してください。

* The "print" statement writes the value of the expression(s) it is
  given.  It differs from just writing the expression you want to
  write (as we did earlier in the calculator examples) in the way it
  handles multiple expressions and strings.  Strings are printed
  without quotes, and a space is inserted between items, so you can
  format things nicely, like this:

     >>> i = 256*256
     >>> print 'The value of i is', i
     The value of i is 65536

  A trailing comma avoids the newline after the output:

     >>> a, b = 0, 1
     >>> while b < 1000:
     ...     print b,
     ...     a, b = b, a+b
     ...
     1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

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

-[ 脚注 ]-

[1] "**" は "-" より優先順位が高いので、"-3**2" は "-(3**2)" と解
    釈さ れ、計算結果は "-9" になります。これを避けて "9" を得たければ
    、 "(-3)**2" と書けば良いです。

[2] 他の言語と違って、"\n" のような特殊文字は単引用符 ("'...'") と
    二重 引用符 (""..."") で同じ意味を持ちます。両者の唯一の違いは、単
    引用 符で囲われた箇所では """ をエスケープする必要がない (ただし
    "\'" はエスケープする必要がある) ことで、逆もまた同様です。
