{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 形式ばらない Python の紹介\n", "[[英語の原文](https://docs.python.org/3.5/tutorial/introduction.html)]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "このマニュアルにある例の多くは、対話プロンプトで入力されるものでもコメントを含んでいます。 Python におけるコメント文はハッシュ文字 # で始まり、物理行の終わりまで続きます。コメントは行の先頭にも、空白やコードの後にも書くことができますが、文字列リテラルの内部に置くことはできません。文字列リテラル中のハッシュ文字はただのハッシュ文字です。コメントはコードを明快にするためのものであり、Pythonはコメントを解釈しません。なので、コードサンプルを実際に入力して試して見るときは、コメントをを省いても大丈夫です。\n", "\n", "いくつかの例です:" ] }, { "cell_type": "code", "execution_count": 73, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# This is the first comment\n", "spam = 1 # and this is the second comment\n", " # ... and now a third!\n", "text = \"# This is not a comment because it's inside quotes.\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python を電卓として使う\n", "\n", "それでは、簡単な Python コマンドをいくつか試しましょう。インタプリタを起動して、一次プロンプト、 >>> が現れるのを待ちます。 (そう長くはかからないはずです)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 数\n", "\n", "インタプリタは単純な電卓のように動作します: 式を入力すると、その結果が表示されます。式の文法は素直なものです: 演算子 `+`, `-`, `*`, `/` は (Pascal や C といった) 他のほとんどの言語と同じように動作します; 丸括弧 (`()`) をグループ化に使うこともできます。例えば:" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 74, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 + 2" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "20" ] }, "execution_count": 75, "metadata": {}, "output_type": "execute_result" } ], "source": [ "50 - 5*6" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5.0" ] }, "execution_count": 76, "metadata": {}, "output_type": "execute_result" } ], "source": [ "(50 - 5*6) / 4" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.6" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "8 / 5 # Division always returns a floating point number." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "整数 (例えば、 `2`, `4`, `20`) は [`int`](https://docs.python.org/3.5/library/functions.html#int)型を持ち、小数部を持つ数 (例えば、 `5.0`, `1.6`) は [`float`](https://docs.python.org/3.5/library/functions.html#float)型を持ちます。数値型については後のチュートリアルでさらに見ていきます。\n", "\n", "除算 (`/`) は常に浮動小数点数を返します。 [floor division](https://docs.python.org/3.5/glossary.html#term-floor-division)を行い、(小数部を切り捨てて) 整数を返すには、 `//` 演算子を使うことができます; 剰余を計算するには `%` を使うことができます:" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5.666666666666667" ] }, "execution_count": 78, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 / 3 # Classic division returns a float." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "5" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 // 3 # Floor division discards the fractional part." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "17 % 3 # The % operator returns the remainder of the division." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "17" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 * 3 + 2 # result * divisor + remainder" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python では、冪乗を計算するのに `**` 演算子が使えます:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 ** 2 # 5 squared" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "128" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 ** 7 # 2 to the power of 7" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Do note that `**` has higher precedence than `-`, so if you want a negative base you will need parentheses:\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "-3**2 # Same as -(3**2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "(-3)**2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "等号 (`=`) は変数に値を代入するときに使います。代入を行っても、次のプロンプトの手前には結果は出力されません:" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "900" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "width = 20\n", "height = 5 * 9\n", "width * height" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "変数が \"定義\" されて (つまり値が代入されて) いない場合、その変数を使おうとするとエラーが発生します:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'n' is not defined", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mn\u001b[0m \u001b[0;31m# Try to access an undefined variable.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mNameError\u001b[0m: name 'n' is not defined" ] } ], "source": [ "n # Try to access an undefined variable." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "浮動小数点を完全にサポートしています。演算対象の値(オペランド)の型が統一されていない場合、演算子は整数のオペランドを浮動小数点型に変換します:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "7.5" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "3 * 3.75 / 1.5" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3.5" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "7.0 / 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "対話モードでは、最後に表示された結果は変数 `_` に代入されます。このことを利用すると、Python を電卓として使うときに、計算を連続して行う作業が多少楽になります。以下に例を示します:" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "12.5625" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "tax = 12.5 / 100\n", "price = 100.50\n", "price * tax" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "113.0625" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "price + _" ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "113.06" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "round(_, 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "ユーザはこの変数を読取り専用の値として扱うべきです。この変数に明示的な代入を行ってはいけません — そんなことをすれば、同じ名前で元の特別な動作をする組み込み変数を覆い隠してしまうような、別のローカルな変数が生成されてしまいます。\n", "\n", "`int` と `float` に加え、 Python は [`Decimal`](https://docs.python.org/3.5/library/decimal.html#decimal.Decimal) や [`Fraction`](https://docs.python.org/3.5/library/fractions.html#fractions.Fraction) のような他の数値型をサポートしています。 Python はビルトインで [complex numbers(複素数)](https://docs.python.org/3.5/library/stdtypes.html#typesnumeric) もサポートし、 `j` もしくは `J` 接尾辞を使って虚部を示します (例。 `3+5j`)。" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 文字列型 (strings)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "数のほかに、Python は文字列の操作ができ、文字列はいくつもの方法で表現できます。文字列は単引用符 (`'...'`) もしくは二重引用符 (`\"...\"`) で囲み、結果はどちらも同じ文字列になります。 `\\` は引用符をエスケープするのに使います:" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'spam eggs'" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'spam eggs' # Single quotes." ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"doesn't\"" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'doesn\\'t' # Use \\' to escape the single quote..." ] }, { "cell_type": "code", "execution_count": 25, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "\"doesn't\"" ] }, "execution_count": 25, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"doesn't\" # ...or use double quotes instead." ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"Yes,\" he said.'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'\"Yes,\" he said.'" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"Yes,\" he said.'" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "\"\\\"Yes,\\\" he said.\"" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"Isn\\'t,\" she said.'" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'\"Isn\\'t,\" she said.'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "対話的インタプリタでは、出力文字列は引用符に囲まれ、特殊文字はバックスラッシュでエスケープされます。これは入力とは違って見える (囲っている引用符が変わる) こともありますが、その 2 つの文字列は同じ文字列です。文字列が単引用符を含み二重引用符を含まない場合、二重引用符で囲われ、それ以外の場合は単引用符で囲われます。 [`print()`](https://docs.python.org/3.5/library/functions.html#print) 関数は、囲っている引用符を落とし、エスケープした特殊文字を出力することで、より読み易い出力を作成します:" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'\"Isn\\'t,\" she said.'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'\"Isn\\'t,\" she said.'" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\"Isn't,\" she said.\n" ] } ], "source": [ "print('\"Isn\\'t,\" she said.')" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "s = 'First line.\\nSecond line.' # \\n means newline.\n", "s # Without print(), \\n is included in the output." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "print(s) # With print(), \\n produces a new line." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "特殊文字として解釈させるために文字の前に `\\` を付けることをしたくない場合は、最初の引用符の前に `r` を付けた raw strings が使えます:" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\some\n", "ame\n" ] } ], "source": [ "print('C:\\some\\name') # Here \\n means newline!" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "C:\\some\\name\n" ] } ], "source": [ "print(r'C:\\some\\name') # Note the r before the quote." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "文字列リテラルは複数行にまたがって書けます。1 つの方法は三連引用符 (`\"\"\"...\"\"\"` や `'''...'''`) を使うことです。行末は自動的に文字列に含まれますが、行末に `\\` を付けることで含めないようにすることもできます。次の例:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "print(\"\"\"\\\n", "Usage: thingy [OPTIONS]\n", " -h Display this usage message\n", " -H hostname Hostname to connect to\n", "\"\"\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "文字列は `+` 演算子で連結させる (くっつけて一つにする) ことができ、`*` 演算子で反復させることができます:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'unununium'" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# 3 times 'un', followed by 'ium'\n", "3 * 'un' + 'ium'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "連続して並んでいる複数の _文字列リテラル_ (つまり、引用符に囲われた文字列) は自動的に連結されます。" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python'" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'Py' 'thon'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "これは 2 つのリテラルどうしに対してのみ働き、変数や式には働きません:" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 2)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m prefix 'thon' # Can't concatenate a variable and a string literal.\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "prefix = 'Py'\n", "prefix 'thon' # Can't concatenate a variable and a string literal." ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 1)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m ('un' * 3) 'ium'\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "('un' * 3) 'ium'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "変数どうしや変数とリテラルを連結したい場合は、`+` を使ってください:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python'" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "prefix = 'Py'\n", "prefix + 'thon'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "この機能は特に、長い文字列を改行したいときに役に立ちます:" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Put several strings within parentheses to have them joined together.'" ] }, "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ "text = ('Put several strings within parentheses '\n", " 'to have them joined together.')\n", "text" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "文字列は _インデクス表記_ (添字表記) することができ、最初の文字のインデクスは 0 になります。文字列型と区別された文字型はありません; 文字というのは単なる長さが 1 の文字列です:" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'P'" ] }, "execution_count": 39, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word = 'Python'\n", "word[0] # Character in position 0." ] }, { "cell_type": "code", "execution_count": 40, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'n'" ] }, "execution_count": 40, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word[5] # Character in position 5." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "インデクスは負の数を指定しても良く、そのときは右から数えていきます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "word[-1] # Last character." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "word[-2] # Second-last character." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "word[-6]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "-0 は 0 と等しいので、負のインデクスは -1 から始まることに注意してください。\n", "\n", "インデクス表記に加え、_スライス_ もサポートされています。インデクス表記は個々の文字を取得するのに使いますが、スライス を使うと部分文字列を取得することができます:" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Py'" ] }, "execution_count": 41, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word[0:2] # Characters from position 0 (included) to 2 (excluded)." ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'tho'" ] }, "execution_count": 42, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word[2:5] # Characters from position 2 (included) to 5 (excluded)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "開始インデクスは常に含まれ、終了インデクスは常に含まれないことに注意してください。なので `s[:i] + s[i:]` が常に s と等しい、ということになります:" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python'" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word[:2] + word[2:]" ] }, { "cell_type": "code", "execution_count": 44, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Python'" ] }, "execution_count": 44, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word[:4] + word[4:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "スライスのインデクスには便利なデフォルト値があります; 最初のインデクスを省略すると、0 と見なされます。第 2 のインデクスを省略すると、スライスしようとする文字列のサイズとみなされます。" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "word[:2] # Character from the beginning to position 2 (excluded)." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "word[4:] # Characters from position 4 (included) to the end." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "word[-2:] # Characters from the second-last (included) to the end." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "スライスの働きかたをおぼえる良い方法は、インデクスが文字と文字の あいだ (between) を指しており、最初の文字の左端が 0 になっていると考えることです。そうすると、 _n_ 文字からなる文字列中の最後の文字の右端はインデクス _n_ となります。例えばこうです:" ] }, { "cell_type": "raw", "metadata": {}, "source": [ " +---+---+---+---+---+---+\n", " | P | y | t | h | o | n |\n", " +---+---+---+---+---+---+\n", " 0 1 2 3 4 5 6\n", "-6 -5 -4 -3 -2 -1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "1行目の数字は文字列の 0 から 6 までのインデクスの位置を示しています; 2行目は対応する負のインデクスを示しています。_i_ から _j_ までのスライスは、それぞれ _i_ と付いた境界から _j_ と付いた境界までの全ての文字から成っています。\n", "\n", "非負のインデクス対の場合、スライスされたシーケンスの長さは、スライスの両端のインデクスが範囲内にあるかぎり、インデクス間の差になります。例えば、 `word[1:3]` の長さは 2 になります。\n", "\n", "大き過ぎるインデクスを使おうとするとエラーが発生します:" ] }, { "cell_type": "code", "execution_count": 45, "metadata": {}, "outputs": [ { "ename": "IndexError", "evalue": "string index out of range", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mIndexError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mword\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m42\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;31m# The word only has 6 characters.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mIndexError\u001b[0m: string index out of range" ] } ], "source": [ "word[42] # The word only has 6 characters." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "しかし、スライスで範囲外のインデクスを使ったときは上手く対応して扱ってくれます:" ] }, { "cell_type": "code", "execution_count": 48, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'on'" ] }, "execution_count": 48, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word[4:42]" ] }, { "cell_type": "code", "execution_count": 49, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "''" ] }, "execution_count": 49, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word[42:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python の文字列は変更できません – つまり不変 ([immutable](https://docs.python.org/3.5/glossary.html#term-immutable)) なのです。従って、文字列のインデクスで指定したある場所に代入を行うとエラーが発生します:" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'str' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mword\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m0\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'J'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment" ] } ], "source": [ "word[0] = 'J'" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'str' object does not support item assignment", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mword\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'py'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment" ] } ], "source": [ "word[2:] = 'py'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "元の文字列と別の文字列が必要な場合は、新しく文字列を作成してください:" ] }, { "cell_type": "code", "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'Jython'" ] }, "execution_count": 52, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'J' + word[1:]" ] }, { "cell_type": "code", "execution_count": 53, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'PyPy'" ] }, "execution_count": 53, "metadata": {}, "output_type": "execute_result" } ], "source": [ "word[:2] + 'Py'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The built-in function returns the length of a string:\n", "組込み関数 [`len()`](https://docs.python.org/3.5/library/functions.html#len) は文字列の長さ (length) を返します:" ] }, { "cell_type": "code", "execution_count": 54, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "34" ] }, "execution_count": 54, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s = 'supercalifragilisticexpialidocious'\n", "len(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__参考:__\n", "\n", "- [テキストシーケンス型 — str](https://docs.python.org/3.5/library/stdtypes.html#textseq): 文字列は シーケンス型 の例であり、シーケンス型でサポートされている共通の操作をサポートしています。\n", "- [文字列メソッド](https://docs.python.org/3.5/library/stdtypes.html#string-methods): 文字列は、基本的な変換や検索を行うための数多くのメソッドをサポートしています。\n", "- [フォーマット済み文字列リテラル](https://docs.python.jp/3/reference/lexical_analysis.html#f-strings): 埋め込み式を持つ文字列リテラル\n", "- [書式指定文字列の文法](https://docs.python.org/3.5/library/string.html#formatstrings): [`str.format()`](https://docs.python.org/3.5/library/string.html#formatstrings)を使った文字列のフォーマットについての情報があります。\n", "- [printf 形式の文字列書式化](https://docs.python.org/3.5/library/stdtypes.html#old-string-formatting): 文字列が `%` 演算子の左オペランドである場合に呼び出される古いフォーマット操作について、詳しく記述されています。 " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### リスト型 (lists)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python 多くの 複合 (_compound_) データ型を備えており、複数の値をまとめるのに使われます。最も汎用性が高いのは リスト ([_list_](https://docs.python.org/3.5/library/stdtypes.html#typesseq-list)) で、コンマ区切りの値 (要素) の並びを角括弧で囲んだものとして書き表されます。リストは異なる型の要素を含むこともありますが、通常は全ての要素は同じ型を持ちます。" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25]" ] }, "execution_count": 55, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares = [1, 4, 9, 16, 25]\n", "squares" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "文字列 (や他の全てのビルトインのシーケンス ([sequence](https://docs.python.org/3.5/glossary.html#term-sequence)) 型) のように、リストはインデクス表記やスライス表記ができます:" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 56, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares[0] # Indexing returns the item." ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "25" ] }, "execution_count": 57, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares[-1]" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[9, 16, 25]" ] }, "execution_count": 58, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares[-3:] # Slicing returns a new list." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "全てのスライス操作は指定された要素を含む新しいリストを返します。これは、次のスライスはリストの新しい (浅い) コピーを返すことを意味します:" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25]" ] }, "execution_count": 59, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares[:]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "リストは文字列の連結に似た操作もサポートしています:" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" ] }, "execution_count": 60, "metadata": {}, "output_type": "execute_result" } ], "source": [ "squares + [36, 49, 64, 81, 100]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "不変 ([immutable](https://docs.python.org/3.5/glossary.html#term-immutable)) な文字列とは違って、リストは可変 ([mutable](https://docs.python.org/3.5/glossary.html#term-mutable)) 型、つまり含んでいる要素を取り替えることができます:" ] }, { "cell_type": "code", "execution_count": 61, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "64" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "cubes = [1, 8, 27, 65, 125] # Something's wrong here ...\n", "4 ** 3 # the cube of 4 is 64, not 65!" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 8, 27, 64, 125]" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "cubes[3] = 64 # Replace the wrong value.\n", "cubes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "`append()` を使って、リストの末尾に新しい要素を追加することもできます (このメソッドについては後で詳しく見ていきます):" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[1, 8, 27, 64, 125, 216, 343]" ] }, "execution_count": 63, "metadata": {}, "output_type": "execute_result" } ], "source": [ "cubes.append(216) # Add the cube of 6 ...\n", "cubes.append(7 ** 3) # and the cube of 7.\n", "cubes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "スライスに代入することもできます。スライスの代入を行って、リストのサイズを変更したり、完全に消すことさえできます:" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c', 'd', 'e', 'f', 'g']" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']\n", "letters" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'C', 'D', 'E', 'f', 'g']" ] }, "execution_count": 65, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Replace some values.\n", "letters[2:5] = ['C', 'D', 'E']\n", "letters" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'f', 'g']" ] }, "execution_count": 66, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Now remove them.\n", "letters[2:5] = []\n", "letters" ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[]" ] }, "execution_count": 67, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Clear the list by replacing all the elements with an empty list.\n", "letters[:] = []\n", "letters" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "組込み関数 [`len()`](https://docs.python.org/3.5/library/functions.html#len) はリストにも適用できます:" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "letters = ['a', 'b', 'c', 'd']\n", "len(letters)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "リストを入れ子にする (ほかのリストを含むリストを造る) ことも可能です。例えば:" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[['a', 'b', 'c'], [1, 2, 3]]" ] }, "execution_count": 69, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = ['a', 'b', 'c']\n", "n = [1, 2, 3]\n", "x = [a, n]\n", "x" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['a', 'b', 'c']" ] }, "execution_count": 70, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x[0]" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'b'" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x[0][1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## プログラミングへの第一歩" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "もちろん、2 たす 2 よりももっと複雑な仕事にも Python を使うことができます。Fibonacci 級数列の先頭の部分列は次のようにして書くことができます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Fibonacci series:\n", "# the sum of two elements defines the next.\n", "a, b = 0, 1\n", "while b < 10:\n", " print(b)\n", " a, b = b, a+b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "上の例では、いくつか新しい機能を取り入れています。\n", "\n", "- 最初の行には 複数同時の代入 (multiple assignment) が入っています: 変数 `a` と `b` は、それぞれ同時に新しい値 0 と 1 になっています。この代入は最後の行でも再度使われており、代入が行われる前に右辺の式がまず評価されます。右辺の式は左から右へと順番に評価されます。\n", "\n", "- [`while`](https://docs.python.org/3.5/reference/compound_stmts.html#while) は、条件 (ここでは `b < 10`) が真である限り実行を繰り返し (ループし) ます。Python では、C 言語と同様に、ゼロでない整数値は真となり、ゼロは偽です。条件式は文字列値やリスト値、実際には任意のシーケンス型でもかまいません。 1つ以上の長さのシーケンスは真で、空のシーケンスは偽になります。例中で使われている条件テストはシンプルな比較です。標準的な比較演算子は C 言語と同様です: すなわち、 `<` (より小さい)、 `>` (より大きい)、 `==` (等しい)、 `<=` (より小さいか等しい)、 `>=` (より大きいか等しい)、および `!=` (等しくない)、です。\n", "\n", "- ループの 本体 (body) は インデント (indent, 字下げ) されています: インデントは Python において実行文をグループにまとめる方法です。対話的プロンプトでは、インデントされた各行を入力するにはタブや (複数個の) スペースを使わなければなりません。実際には、Python へのより複雑な入力を準備するにはテキストエディタを使うことになるでしょう; ほとんどのテキストエディタは自動インデント機能を持っています。複合文を対話的に入力するときには、(パーザはいつ最後の行を入力したのか推し量ることができないので) 入力の完了を示すために最後に空行を続けなければなりません。基本ブロックの各行は同じだけインデントされていなければならないので注意してください。\n", "\n", "- [`print()`](https://docs.python.org/3.5/library/functions.html#print) 関数は与えられた引数の値を書き出します。これは (前に電卓の例でやったような) 単に出力したい式を書くのとは、複数の引数や浮動小数点量や文字列に対する扱い方が違います。文字列は引用符無しで出力され、要素の間に空白が挿入されて、このように出力の書式が整えられます:" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "i = 256*256\n", "print('The value of i is', i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "キーワード引数 `end` を使うと、出力の末尾に改行文字を出力しないようにしたり、別の文字列を末尾に出力したりできます:" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987," ] } ], "source": [ "a, b = 0, 1\n", "while b < 1000:\n", " print(b, end=',')\n", " a, b = b, a+b" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.3" } }, "nbformat": 4, "nbformat_minor": 1 }