{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# pythonの基本\n", "
\n", "© H. Toyoki (2018,2019)\n", "
\n", "\n", "The original juypter notebook of this page is [here](basics_python.ipynb)" ] }, { "cell_type": "markdown", "metadata": { "toc": "true" }, "source": [ "

Table of Contents

\n", "
" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 実習の方法\n", "\n", "プログラム例が載っている教材は基本的にjupyter notebookにて作成し、notebook形式のファイルを公開する。このノートブックについては、上記の「here」をクリックしてダウンロードできる。\n", "\n", "ダウンロードしたノートブックを実習用のフォルダを「ドキュメント」の下につくり、そこに置けば、各端末のjupyter notebookを立ち上げることにより読み込み、実行できる。\n", "\n", "また、各自、新しいセルにて種々試すことができる。\n", "\n", "プログラムコードの間に説明文があると思考の妨げになると感じたならば、独自の新規ノートブックを作成し、教材のページ(あるいはノートブック)を参照しながら、新しいノートブック内で試すのが良いだろう。もちろん、jupyter notebookではなく、別のエディタとコマンドラインツール(ipython)や統合開発環境で実行してみてもよい。\n", "\n", "\n", "**毎回試したことを、各自のJupyter notebookに記録し、8回の講義終了時に提出する**\n", "\n", "\n", "初めての人は、以下の文章にそって、基本的な文法を修得する。\n", "\n", "なれている人は、\n", " - PEPについて一通り学習する\n", " - このページに記載していないpythonコードの書き方について、他の人に教えるつもりで、ノートブックを作成してみる。\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Jupyterの利用\n", "\n", "Jupyter notebookは、\n", " - セルと呼ばれる区画にプログラムの一部分あるいは全部を書く\n", " - セルには、(1) pythonプログラムコードを書く、(2) 文章を書くという2つの種類の特性があり、それは\"Cell\"メニューによって切り替える\n", " - 文章はMarkdownという文法に則って書く。\n", "\n", "Jupyter Notebookの使い方に関する情報はWeb上に山ほどあるので、自分の好みにあったものを参照してほしい。\n", "たとえば、https://qiita.com/takuyanin/items/8bf396e7b6b051670147\n", "\n", "初めての人は、それから始めてもよい。\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 基本的な変数\n", "\n", " - 変数宣言は要らない\n", " - 変数名に値を代入したときに生成\n", " - 型は値によって決まる\n", " - 型変換の関数はいろいろ用意されている str(x), float(x), int(x), ...\n", " - print文の書式は以下を参照" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "60.16\n", "weight: 60.2\n", "Hello, Nashidai Taro.\n", "Your age, height, and weight are 25, and 1.705 m, 60.2 kg, respectively.\n", "BMI = 20.694696468038625\n" ] } ], "source": [ "myname = \"Nashidai Taro\"\n", "age = 25\n", "height = 1.705\n", "weight = 60.16\n", "formatted_weight = \"weight: %6.1f\" % weight\n", "print( weight )\n", "print( formatted_weight )\n", "print( \"Hello, %s.\" % myname )\n", "print( \"Your age, height, and weight are %2d, and %6.3f m, %6.1f kg, respectively.\" % (age, height, weight) )\n", "\n", "# 演算\n", "bmi = weight / height**2\n", "print(\"BMI = \" + str(bmi))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 配列 list と dictionary\n", "\n", "### 単純な一次元配列 list\n", " - [ ] で要素を並べる\n", " - 各要素の参照は a[2] のようにする。\n", " - 部分リスト a[2:5], a[:5], のような記述が可能 (スライスと呼ぶ)\n", " - 逆からのインデックスが可能 a[-2] のような\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "a = ['red', 'blue', 'green', 'black', 'white']" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "green\n", "['green', 'black']\n", "['black', 'white']\n", "black\n" ] } ], "source": [ "print(a[2])\n", "print(a[2:4])\n", "print(a[3:])\n", "print(a[-2])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 辞書 dictionary\n", "\n", " - 他のスクリプト言語で、連想配列(associative array)、ハッシュ(hash)と呼ばれるものと同様\n", " - キーと値をセットで記憶\n", " - 値として様々な型の混在が可能\n", " - 値がリストや配列でもよい" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "person = {\"name\": \"Suzuki\", \"hobby\": [\"ski\", \"tennis\", \"piano\"], \"age\": 20, \"weight\": 70}" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Suzuki\n", "['ski', 'tennis', 'piano']\n" ] } ], "source": [ "print(person[\"name\"])\n", "print(person[\"hobby\"])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### リストや辞書の演算\n", "\n", "リストや辞書の連結、要素の追加、削除を行う様々な関数(メソッド)が用意されている\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### データ分析や数値計算に便利なデータ構造の拡張\n", "\n", "pythonネイティブのデータ構造リスト・辞書だけでは、大量のデータや数値計算には使いにくい。\n", "\n", "そのような用途向けに、いくつかのモジュールで配列に類するデータ構造の拡張が行われている。\n", "\n", "ここでは、良く用いらえれる2種類(実用上ほぼそれでOK)のモジュールを使う。\n", "\n", "- numpy\n", " - Cなどのプログラミング言語の配列ににたndarrayが用意されている。\n", " - 最初は、作成の方法に戸惑うだろう。初期化を行うメソッドとして、\n", " - zeros(全部ゼロで初期化)\n", " - ones (全部1で初期化)\n", " - linspace (ある値の区間を等間隔に値をセット)\n", " などがある。\n", " たとえば http://www.turbare.net/transl/scipy-lecture-notes/intro/numpy/array_object.html#numpy-arrays\n", " \n", "- pandas\n", " - データ分析に都合がよいDataFrmame(2次元的)とSeries(1次元的)というデータ構造がある。\n", " - DataFrameとそれに付随するメソッドはとても便利だが、列・行には特別な意味があり、最初は戸惑うだろう。\n", " たとえば、https://qiita.com/ysdyt/items/9ccca82fc5b504e7913a\n", " " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 制御構造\n", "### 反復と条件分岐\n", "\n", " - プログラム単位はインデントで表す (Cのような、{ }や;はない!)\n", " - コードの見やすさのために、1行は80文字以内にすることが推奨されている\n", " - 継続行は行末に \\ をおくことで実現できるが、あまり推奨されない。代わりに( )を上手に用いる\n", " - whileの書き方はほぼ同じだがforは異なる\n", " - if/elif/elseはほぼ同じ\n", " - 繰り返し文のなかのbreak, continueはほぼ同じ\n", " " ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(-134+352j)\n" ] } ], "source": [ "z = 1 + 1j # complex number\n", "while abs(z) < 100:\n", " if z.imag == 0:\n", " break\n", " z = z**2 +1\n", "print(z)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "A lot\n" ] } ], "source": [ "a = 10\n", "if a == 1:\n", " print(1)\n", "elif a == 2:\n", " print(2)\n", "else:\n", " print(\"A lot\")" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "4\n" ] } ], "source": [ "for i in range(5):\n", " print(i)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "range(5)は0から1ずつ増やした5個の要素をもつ。\n", "\n", "(注)\n", "\n", "ちょっとわかりにくいが正確にいうと、rangeはrange型のobjectを生成するので、リストに変換するにはlist()という関数を用いる必要がある。\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "range(0, 5)\n", "[0, 1, 2, 3, 4]\n" ] } ], "source": [ "a = range(5)\n", "print(a)\n", "b = list(a)\n", "print(b)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 辞書や配列の要素を走査する繰り返し\n", "\n", "要素の数はlen()関数で得られるのでそれを利用する場合もある。" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1.0\n", "0.5\n", "0.3333333333333333\n", "0.25\n" ] } ], "source": [ "a = [1, 2, 3, 4]\n", "for x in a:\n", " print(1. / x) " ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 2\n", "1 4\n", "2 6\n", "3 8\n" ] } ], "source": [ "a = [2,4,6,8]\n", "for n in range(len(a)):\n", " print(n, a[n])\n", " " ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "math = 80\n", "phys = 70\n", "chem = 90\n", "bio = 60\n" ] } ], "source": [ "point = {\"math\": 80, \"phys\": 70, \"chem\": 90, \"bio\": 60}\n", "for key, value in point.items():\n", " print(\"%s = %d\" % (key, value))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "pointという辞書(オブジェクト)に対してitems()というメソッドが付随しており、それが実行されたと解する。\n", "\n", "point.values()\n", "\n", "単に、つぎのようにしてもよい。 \n", "\n", "注:\n", "\n", "items()関数の返値の型はdict_itemsで、直接、その要素を取り出せません。\"in\"とともに用います。たぶん。(pythonにはこのような特別な型が多くあり、慣れにくい気がします。)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "math = 80\n", "phys = 70\n", "chem = 90\n", "bio = 60\n" ] } ], "source": [ "for key in point:\n", " print(\"%s = %d\" % (key, point[key]))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 高速な処理のために\n", "\n", "pythonは他のインタプリタ型言語と同様、繰り返しや条件分岐などの処理は遅い。\n", "\n", "したがって、大量のデータを繰り返し処理する場合は、forやwhile分の利用を極力避け、numpy, pandasなどのモジュールに備わっているメソッドを利用する。\n", "\n", "ちょっとした解説 https://8tops.yamanashi.ac.jp/~toyoki/lectures/simulationMethods/speedup4matrices.html\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 関数\n", "\n", "引数に既定値を与えておくと、引数の数が欠けている場合も対応できる。" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "13.0\n", "12.0\n", "17.0\n" ] } ], "source": [ "def lin_func(x=1, y=1):\n", " return 2.0* x + 3.0*y\n", "\n", "print(lin_func(2,3))\n", "print(lin_func(x=3, y=2))\n", "print(lin_func(y=5))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Other tutorials and documents\n", "\n", "### A useful tutorial for scientific use\n", "http://www.scipy-lectures.org/\n", "\n", "and its Japanese translation\n", "\n", "http://www.turbare.net/transl/scipy-lecture-notes/index.html\n", "\n", "### Official python documents\n", "\n", "https://docs.python.jp/3/index.html\n", "\n", "https://docs.python.jp/2/index.html\n", "\n", "### Python Style Guide: PEP (Python Enhancement Proposals)\n", "\n", "Pythonは、プログラムのブロックを{ }ではなくインデントの深さで表すので、コードを書くにあたって行の長さ、複数行のにわたる命令の書き方が可読性の上でとても重要です。\n", "\n", "多くのエディタでは、左括弧\"(\", \"{\", '\\['が閉じない状態で開業すると適当なインデントを挿入してくれます。pythonインタプリタは、継続行のサインである行末の\"\\\\\"がなくても継続行と判断しますので、それをつけないでもOKです。\n", "\n", "ということで、\n", "\n", " - 行は80字未満にする\n", " - 括弧を上手に使って継続行の記述をする。\n", " - その際、行頭の位置をそろえる。\n", "\n", "ということが作法として推奨されています。\n", "\n", "くれぐれも長い行を書かないように気をつけましょう。(印刷物やスライドなどで示す場合にも役立ちます。)\n", "\n", "詳しくはPEP文書をみてください。\n", "\n", "http://pep8-ja.readthedocs.io/ja/latest/\n", "\n", "https://legacy.python.org/dev/peps/pep-0008/\n", "\n", "短縮版として次のようなページも参考になる。\n", "https://www.yoheim.net/blog.php?q=20160612\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.6.13" }, "toc": { "base_numbering": 1, "nav_menu": { "height": "12px", "width": "252px" }, "number_sections": true, "sideBar": true, "skip_h1_title": true, "title_cell": "Table of Contents", "title_sidebar": "Contents", "toc_cell": true, "toc_position": { "height": "775px", "left": "0px", "right": "1275px", "top": "111px", "width": "165px" }, "toc_section_display": "block", "toc_window_display": true } }, "nbformat": 4, "nbformat_minor": 2 }