Skip to content

Instantly share code, notes, and snippets.

@miyamoto-yuichiro
Last active April 1, 2019 11:13
Show Gist options
  • Save miyamoto-yuichiro/1a280249850b7c69efd85dc8c42c3025 to your computer and use it in GitHub Desktop.
Save miyamoto-yuichiro/1a280249850b7c69efd85dc8c42c3025 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# とりあえずPython interactive shellを使ってみる"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## まずは四則演算など"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 1,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"1 + 2"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"-1"
]
},
"execution_count": 2,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"1 - 2"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"21"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"7 * 3"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2.3333333333333335"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"7 / 3"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ここまでで,少なくとも電卓の代わりになりそうだとわかる.\n",
"<!--なお,Python2.7系の場合は,最後の割り算の結果は2となる.-->\n",
"\n",
"四則演算ほど基本的ではないが,べき乗,商,余りなどの演算子も用意されている."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"2 ** 3 # 2の3乗は8"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"7 // 3 # 7を3で割った商は2"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"7 % 3 # 7を3で割った余りは1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"見て分かる通り,Pythonでは,#以降行末まではコメントとして扱われる.\n",
"\n",
"演算の優先順位を括弧()で指定できる."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"10.0"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"(3 - 7 / 4) * 8"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"-11.0"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"3 - 7 / 4 * 8"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 変数の利用"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"一度の命令では複雑な計算はやりづらい.\n",
"変数を利用すると,前の計算結果をつぎつぎと利用して,複雑な計算をできる."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"x = 3"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [],
"source": [
"y = x + 4"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"7"
]
},
"execution_count": 13,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pythonでは,他の多くのプログラミング言語と同様に,=の右辺を=の左辺に代入する.\n",
"(正確に言うと代入ではなく名前の付替えなのだが,それはいずれ説明する.)\n",
"左辺には変数を,右辺には式を書く.\n",
"少なくとも1度代入された変数を単独で呼ぶと,その値が出力される.\n",
"Pythonのキーワード(今後紹介するfor,ifなど)以外の文字の列は,新たな変数とみなされる.\n",
"すなわち,Pythonでは変数宣言は必要ない."
]
},
{
"cell_type": "code",
"execution_count": 14,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'z' 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<ipython-input-14-3a710d2a84f8>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mz\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'z' is not defined"
]
}
],
"source": [
"z"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ただし,一度も代入されていない文字の列は,未定義な何かとみなされてエラーとなる."
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {},
"outputs": [],
"source": [
"z = x * y"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"21"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"z"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [],
"source": [
"miya = 'yuichiro'"
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'yuichiro'"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"miya"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pythonで,値としての文字列を扱いたい場合には,シングルクォーテーションで囲む.\n",
"あるいはダブルクオーテーションで囲む."
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"japan = \"nippon\""
]
},
{
"cell_type": "code",
"execution_count": 20,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'nippon'"
]
},
"execution_count": 20,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"japan"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"文字列の中にシングルクォーテーションそのものを入れたい場合にはダブルクオーテーションを使うのが良い."
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [],
"source": [
"tonight = \"kon'ya\""
]
},
{
"cell_type": "code",
"execution_count": 22,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"kon'ya\""
]
},
"execution_count": 22,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"tonight"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## リストの利用"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"複数データを扱うためのPythonにおける最も基本的な構造はリストである.\n",
"例えば,数字の列3, 1, 4を変数xに代入したければ以下のようにする."
]
},
{
"cell_type": "code",
"execution_count": 23,
"metadata": {},
"outputs": [],
"source": [
"x = [3, 1, 4]"
]
},
{
"cell_type": "code",
"execution_count": 24,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[3, 1, 4]"
]
},
"execution_count": 24,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"リストの要素には数字だけでなく,文字列やその他のもの,例えばリストそのものも使える.\n",
"また,1つのリストの中で要素の種類が異なっていても問題ない."
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [],
"source": [
"x = [3.14, 'abc', 8, [1, 2, 3]]"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[3.14, 'abc', 8, [1, 2, 3]]"
]
},
"execution_count": 26,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"リストの要素には,添字の指定でアクセスできる.\n",
"Pythonのリストの添字は,C言語やJavaと同様に,0始まりである."
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'abc'"
]
},
"execution_count": 27,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[1]"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 28,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[3][0]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"添字を指定して代入すれば,リストそのものを部分的に書き換えられる."
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [],
"source": [
"x[2] = 'de'"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[3.14, 'abc', 'de', [1, 2, 3]]"
]
},
"execution_count": 30,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pythonでは,C言語と異なり,-1という添字で最後の要素にアクセスできる.\n",
"これは便利である."
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[1, 2, 3]"
]
},
"execution_count": 31,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"リストにはスライスという機能があり,添字の範囲指定で,リストの部分列を取り出せる."
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['abc', 'de']"
]
},
"execution_count": 32,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[1:3]"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"['de', [1, 2, 3]]"
]
},
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[2:]"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[3.14, 'abc', 'de']"
]
},
"execution_count": 34,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[:-1]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"x[1:3]はリストxの添字1番から2番(3番の手前)までである.\n",
"範囲の最後や最初を省略できる.\n",
"x[2:]はリストxの添字2番から最後までである.\n",
"x[:-1]はリストxの最初から,最後の手前までである."
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[3.14, 'abc', 'de', [1, 2, 3]]"
]
},
"execution_count": 35,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x[:]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"範囲の最初と最後の両方を省略するとリスト全体のスライスとなる.\n",
"これは一見意味が無いように思えるかもしれない.\n",
"しかし,リストのスライスはリストの(浅い)コピーを暗に作っているので,リストをコピーしたい場合には重宝する."
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[3.14, 'abc', 'de', [1, 2, 3], 3.14, 'abc', 'de', [1, 2, 3]]"
]
},
"execution_count": 36,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"x + x"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"リストは+演算子で連結できる."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 文字列の利用"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"文字列は文字のリストとでも言うべき扱いになっている."
]
},
{
"cell_type": "code",
"execution_count": 37,
"metadata": {},
"outputs": [],
"source": [
"miyamoto = 'yuichiro'"
]
},
{
"cell_type": "code",
"execution_count": 38,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'c'"
]
},
"execution_count": 38,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"miyamoto[3]"
]
},
{
"cell_type": "code",
"execution_count": 39,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'o'"
]
},
"execution_count": 39,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"miyamoto[-1]"
]
},
{
"cell_type": "code",
"execution_count": 40,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ichir'"
]
},
"execution_count": 40,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"miyamoto[2:7]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ただし,文字列はリストと異なり,変更はできない(immutableである)."
]
},
{
"cell_type": "code",
"execution_count": 41,
"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<ipython-input-41-a072e40b15fb>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mmiyamoto\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m3\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'a'\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": [
"miyamoto[3] = 'a'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"文字列を変更したければ,新たに作って代入するしかない."
]
},
{
"cell_type": "code",
"execution_count": 42,
"metadata": {},
"outputs": [],
"source": [
"miyamoto = miyamoto[:3] + 'a' + miyamoto[4:] # 2文字目まで + 'a' + 4文字目以降"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'yuiahiro'"
]
},
"execution_count": 43,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"miyamoto"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"miyamoto = 'yuichiro' # あとの説明のために戻しておく."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 組み込み関数の利用"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pythonには予め用意されている関数がある."
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4"
]
},
"execution_count": 45,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(x) # lenはリストや文字列の要素数を返す関数"
]
},
{
"cell_type": "code",
"execution_count": 46,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"8"
]
},
"execution_count": 46,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"len(miyamoto)"
]
},
{
"cell_type": "code",
"execution_count": 47,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"6"
]
},
"execution_count": 47,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"sum(x[-1]) # sumはリストの要素の合計を返す関数,リストの要素は合計を計算できるようなものに限る."
]
},
{
"cell_type": "code",
"execution_count": 48,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3"
]
},
"execution_count": 48,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"max(x[-1]) # maxはリストの最大の要素を返す関数"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1"
]
},
"execution_count": 49,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"min(x[-1]) # minはリストの最小の要素を返す関数"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'c'"
]
},
"execution_count": 50,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"min(miyamoto) # 文字の場合は辞書順で大きさが評価されるようだ."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"組み込み関数は他にもあるが,今回はここまでにしておく."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 標準ライブラリの利用"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Pythonでは,組み込み関数以外にも便利な関数がいろいろ用意されている.\n",
"例えば,平方根や三角関数を計算してくれる数学関数などである.\n",
"組み込み関数ではない関数は,そのままでは使えない.\n",
"予め用意された関数などのかたまり(それらはモジュールとよばれる)を読み込む必要がある.\n",
"ここでは一例として数学関数モジュールmathを読み込んで使ってみる."
]
},
{
"cell_type": "code",
"execution_count": 51,
"metadata": {},
"outputs": [],
"source": [
"import math # 数学関数のモジュールを読み込む."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"モジュールを読み込む命令は\n",
"\n",
"```python\n",
"import モジュール名\n",
"```\n",
"\n",
"である.\n",
"これでそのモジュールを使えるようになる.\n",
"\n",
"モジュールで用意されている関数を使う際には\n",
"\n",
"```python\n",
"モジュール名.関数名\n",
"```\n",
"\n",
"とする.\n",
"\n",
"どのようなモジュールにどのような関数があるのかはインターネットで検索すればわかる."
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"1.4142135623730951"
]
},
"execution_count": 52,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"math.sqrt(2) # 2の平方根"
]
},
{
"cell_type": "code",
"execution_count": 53,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3.141592653589793"
]
},
"execution_count": 53,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"math.pi # 円周率.関数だけでなく定数も用意されている."
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"0.49999999999999994"
]
},
"execution_count": 54,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"math.sin(math.pi / 6) # sin(30°) = 1/2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"数値誤差のため,ピッタリ0.5とはならなかった."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 繰り返しの構文"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ここまでは,単独の命令だけを紹介してきた.\n",
"たとえ既存のモジュールを利用したとしても,単独の命令でできることはたかが知れている.\n",
"プログラムは,繰り返し命令などでたくさんの処理を行えるようになって初めて真価を発揮する.\n",
"最も単純な例として,以下に,5回文字列を表示する命令を記す."
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"yuichiro\n",
"yuichiro\n",
"yuichiro\n",
"yuichiro\n",
"yuichiro\n"
]
}
],
"source": [
"i = 0 # 最初にiに0を代入しておく.\n",
"while i < 5: # whileは繰り返し文のキーワードである.iが5未満の間は以下の2行の命令を繰り返す.2行下で毎回iを1増やしているので結局5回繰り返す.\n",
" print(miyamoto) # printは引数の文字列を表示する組み込み関数である.文字列miyamotoの値,ここでは'yuichiro'を表示する.\n",
" i = i + 1 # iを1増やす."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"上記の例から推測されるように,whileキーワードを用いた繰り返しの構文は \n",
"```python\n",
"while 条件:\n",
" 命令1\n",
" 命令2\n",
" ……\n",
"```\n",
"である.\n",
"条件が満たされる間,命令1,命令2,……が繰り返し実行される.\n",
"繰り返される命令の範囲はインデントで区別される.\n",
"よってPythonのプログラミングにおいては,改行やインデントは重要である.\n",
"これはC言語やJavaとは大きく異る."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"繰り返しの構文にはforキーワードも使える.\n",
"forキーワードで上記と同じ処理を書くと,以下のようになる."
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"yuichiro\n",
"yuichiro\n",
"yuichiro\n",
"yuichiro\n",
"yuichiro\n"
]
}
],
"source": [
"for i in [0, 1, 2, 3, 4]:\n",
" print(miyamoto)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"上記の例から推測されるように,forキーワードを用いた繰り返しの構文は \n",
"```python\n",
"for 変数 in リスト:\n",
" 命令1\n",
" 命令2\n",
" ……\n",
"```\n",
"である.\n",
"リストの要素それぞれを変数に代入した場合に関して,命令1,命令2,……が実行される.\n",
"繰り返される命令の範囲はやはりインデントで区別される.\n",
"よってPythonのプログラミングにおいては,改行やインデントは重要である."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"上記のforを用いた命令は5回繰り返すだけなので,リストは[0, 1, 2, 3, 4]で済んだ.\n",
"しかし,100万回繰り返すなどの場合には,リストを陽に書きたくない.\n",
"このような場合に便利なリスト生成関数(正確にはイテレータ)rangeが組み込み関数として用意されている."
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"yuichiro\n",
"yuichiro\n",
"yuichiro\n",
"yuichiro\n",
"yuichiro\n"
]
}
],
"source": [
"for i in range(5): # range(5)で[0, 1, 2, 3, 4]と同等\n",
" print(miyamoto)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"rangeは\n",
"\n",
"- range(b)で「0から始まり,1ずつ増えて,b未満で終わる整数列」\n",
"- range(a, b)で「aから始まり,1ずつ増えて,b未満で終わる整数列」\n",
"- range(a, b, c)で「aから始まり,cずつ増えて,b未満で終わる整数列」\n",
"\n",
"である.\n",
"\n",
"a, b, cには任意の整数を入れて良い.\n",
"ただし,range(7, 3, 1)とかにすると,7で始まり1ずつ増えて3未満で終わる整数はないので,何もないのと一緒となる.(繰り返されない.)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ただ表示するだけではつまらない.\n",
"\n",
"以下に,1から20までの整数の合計を計算する命令を記す."
]
},
{
"cell_type": "code",
"execution_count": 58,
"metadata": {},
"outputs": [],
"source": [
"s = 0 # sは合計を格納する変数\n",
"y = 1 # yは1から20までの整数が入る関数\n",
"while y <= 20: # whileは繰り返し構文のキーワード\n",
" s = s + y # sをyだけ増やし \n",
" y = y + 1 # yを1増やす"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"210"
]
},
"execution_count": 59,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"参考までに,同じ役割の命令をforを用いて以下に記す."
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {},
"outputs": [],
"source": [
"s = 0\n",
"for i in range(1, 21): # iが1,2,...,20のそれぞれに関して実行される.\n",
" s = s + i"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"210"
]
},
"execution_count": 61,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"s"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 条件分岐"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"次に,条件分岐の構文を紹介する.\n",
"以下に,2017が素数でないならば'2017 is not prime'を表示する命令を記す."
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [],
"source": [
"for i in range(2, 2017): # iが2,3,...,2016のそれぞれに関して以下の3行を実行する.\n",
" if 2017 % i == 0: # 2017がiで割り切れるならば,素数ではないので,\n",
" print('2017 is not prime.') # 素数ではないと表示し\n",
" break # 繰り返しを終了する.命令breakは一番内側の繰り返し(この場合はforによる繰り返し)を終了する."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"実行すると何も表示されないので,どうやら2017は素数であるようだ.\n",
"(時間があったら他の数字でも試してみよう.)\n",
"\n",
"この例から推測されるように,ifキーワードを用いた条件分岐の構文は\n",
"```python\n",
"if 条件:\n",
" 命令1\n",
" 命令2\n",
" ……\n",
"```\n",
"である.\n",
"条件が満たされると,命令1,命令2,……が実行される.\n",
"条件が満たされた場合に実行される命令の範囲はインデントで区別される.\n",
"\n",
"条件分岐は以下の構文でも指定できる.\n",
"```python\n",
"if 条件:\n",
" 命令1-1\n",
" 命令1-2\n",
" ……\n",
"else:\n",
" 命令2-1\n",
" 命令2-2\n",
" ……\n",
"```\n",
"条件が満たされると,命令1-1,命令1-2,……が,条件が満たされないと命令2-1,命令2-2,……が実行される.\n",
"else以下は省略可能である.\n",
"\n",
"先ほどの2017の素数判定はwhileを使うと以下のように書ける."
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {},
"outputs": [],
"source": [
"n = 2017\n",
"i = 2\n",
"while i < n: # 3行下で毎回iを1増やしているので,これは「iが2からn-1のそれぞれに関して繰り返す」ということになる.\n",
" if n % i == 0: # nをiで割った余りが0ならば割り切れるということなので\n",
" print('2017 is not prime.')\n",
" break # 命令breakは一番内側の繰り返し(この場合はwhileによる繰り返し)を終了する\n",
" i = i + 1 # nがiで割り切れないならば,iを1増やして次に備える"
]
},
{
"cell_type": "code",
"execution_count": 64,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2017"
]
},
"execution_count": 64,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"i # ちなみにここでiを表示すると,iには2017が入っている."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"さらに,この素数判定はelseも使うと以下のように書ける."
]
},
{
"cell_type": "code",
"execution_count": 65,
"metadata": {},
"outputs": [],
"source": [
"n = 2017\n",
"i = 2\n",
"while i < n:\n",
" if n % i == 0:\n",
" print('2017 is not prime.')\n",
" break\n",
" else:\n",
" i = i + 1"
]
},
{
"cell_type": "code",
"execution_count": 66,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2017"
]
},
"execution_count": 66,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"i"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"もちろん結果は同じである.\n",
"\n",
"より一般に,2017以外の自然数が素数か否かを判定したい場合には,上記の処理においてnに最初に代入する値を変えれば良い.\n",
"しかし,その都度上記のコードを入力するのは面倒である.\n",
"そのような場合には,上記のコードをまとめたものを自作の関数として定義し,使いまわすと便利である."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 関数の定義と利用"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"まず簡単な関数として,与えられた数の2倍を返す関数twiceを定義して使ってみる.\n",
"\n",
"定義する前にtwiceという関数がすでにあるかないか実際に実行してみる."
]
},
{
"cell_type": "code",
"execution_count": 67,
"metadata": {},
"outputs": [
{
"ename": "NameError",
"evalue": "name 'twice' 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<ipython-input-67-31cf89d7a748>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mtwice\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2017\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mNameError\u001b[0m: name 'twice' is not defined"
]
}
],
"source": [
"twice(2017)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"twiceという名前の関数はないようなので,自分で定義してみる."
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [],
"source": [
"def twice(x):\n",
" y = 2 * x\n",
" return y"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"この例から推測されるように,関数の定義は\n",
"```python\n",
"def 関数名(引数):\n",
" 命令1\n",
" 命令2\n",
" ……\n",
" return 戻り値\n",
"```\n",
"である.\n",
"関数を実行すると,命令1,命令2,……が実行される.\n",
"returnキーワードがきたら,その直後の戻り値を返して関数は終了する.\n",
"\n",
"特に値を戻す必要が無いならば,return命令はなくても良い.\n",
"しかし,後々の保守のためにはreturnを常に書くほうが良い."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"一度定義された関数は,組み込み関数と同様にinteratice shellで使える."
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"4034"
]
},
"execution_count": 69,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"twice(2017)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"このtwiceの例で気がついたかもしれないが,関数の引数の型を指定する必要はない.\n",
"そもそも,Pythonには型を指定する宣言はない.\n",
"では,twiceの引数に整数以外を与えたらどうなるのか?\n",
"\n",
"それは試してみればわかる."
]
},
{
"cell_type": "code",
"execution_count": 70,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"3.0"
]
},
"execution_count": 70,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"twice(1.5)"
]
},
{
"cell_type": "code",
"execution_count": 71,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'yuichiroyuichiro'"
]
},
"execution_count": 71,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"twice(miyamoto)"
]
},
{
"cell_type": "code",
"execution_count": 72,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"[3, 1, 4, 3, 1, 4]"
]
},
"execution_count": 72,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"twice([3, 1, 4])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"つまりここで定義した関数twiceは,数値を2倍する関数ではなく,「Pythonで乗算できるものならば,なんでも2倍する」関数である.\n",
"\n",
"これは便利に見えるが,諸刃の剣である.\n",
"例えば,数値計算が目的なのにちょっとした間違いで文字列などを入れてしまったとしても「計算できる限りPythonは計算し続けてしまう」のである."
]
},
{
"cell_type": "code",
"execution_count": 73,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'These are L o oThese are L o o'"
]
},
"execution_count": 73,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"lOO = 'These are L o o'\n",
"twice(lOO)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"もう少し複雑な関数を定義してみる.\n",
"\n",
"以下に,引数nに2以上の自然数が与えられたとき,nが素数ならば'yes',nが素数でないならば'no'を返す関数is_primeを定義する."
]
},
{
"cell_type": "code",
"execution_count": 74,
"metadata": {},
"outputs": [],
"source": [
"def is_prime(n):\n",
" i = 2\n",
" while i < n:\n",
" if n % i == 0:\n",
" return 'no' # returnは関数を終了する命令としても使える.\n",
" else:\n",
" i = i + 1\n",
" return 'yes' # 関数終了時には,returnの直後に書かれているものが返される."
]
},
{
"cell_type": "code",
"execution_count": 75,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'yes'"
]
},
"execution_count": 75,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"is_prime(2017)"
]
},
{
"cell_type": "code",
"execution_count": 76,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'no'"
]
},
"execution_count": 76,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"is_prime(2019)"
]
},
{
"cell_type": "code",
"execution_count": 77,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'no'"
]
},
"execution_count": 77,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"is_prime(2021)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"素数の年(西暦)は当分先のようである.\n",
"\n",
"ここで,先程のtwiceと同様に,数値ではない値を関数is_primeに与えて実行してみよう."
]
},
{
"cell_type": "code",
"execution_count": 78,
"metadata": {},
"outputs": [
{
"ename": "TypeError",
"evalue": "'<' not supported between instances of 'int' and 'str'",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-78-49224f67b48b>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mis_prime\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmiyamoto\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;32m<ipython-input-74-c04e0dfae60d>\u001b[0m in \u001b[0;36mis_prime\u001b[0;34m(n)\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mis_prime\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mn\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mi\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m2\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mwhile\u001b[0m \u001b[0mi\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0mn\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0mn\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0mi\u001b[0m \u001b[0;34m==\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0;34m'no'\u001b[0m \u001b[0;31m# returnは関数を終了する命令としても使える.\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
"\u001b[0;31mTypeError\u001b[0m: '<' not supported between instances of 'int' and 'str'"
]
}
],
"source": [
"is_prime(miyamoto)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"今度は実行できなかった.\n",
"整数i(=2)と文字列n(=miyamoto='yuichiro')の大小は比較できないからである.\n",
"\n",
"このように,Pythonには型の宣言はないものの,型の概念はある.\n",
"変数の型は「値が代入されたときに,その値に従って」決まる.\n",
"\n",
"定義した関数を用いてより高度な関数を定義できる.\n",
"先ほどの素数判定関数is_primeを用いて,n以下の素数を表示する関数enumerate_prime_simplyを定義する."
]
},
{
"cell_type": "code",
"execution_count": 79,
"metadata": {},
"outputs": [],
"source": [
"def enumerate_prime_simply(n): # この関数のようにreturnのない関数も定義できる\n",
" i = 2\n",
" while i <= n:\n",
" if is_prime(i) == 'yes': # 先ほど定義した関数is_primeを利用\n",
" print(i)\n",
" i = i + 1"
]
},
{
"cell_type": "code",
"execution_count": 80,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n",
"3\n",
"5\n",
"7\n",
"11\n",
"13\n",
"17\n",
"19\n"
]
}
],
"source": [
"enumerate_prime_simply(20)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"ここまでの知識を駆使すれば,より高度な関数を構築できる.\n",
"しかし,このinteractive shellを終えてしまったら,また構築し直しである.\n",
"同じ関数を何度も構築しなくて良くするには,モジュールの構築が役立つ.\n",
"次回は,モジュールの構築,そしてファイル入出力を学ぶ."
]
}
],
"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.7.2"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment