{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 前情提要\n", "\n", "\n", "* 認識 Python\n", "* 基本運算\n", " - 加減乘除\n", " - 取餘數\n", " - 指數\n", " - 複數\n", " - 除法,無條件捨去到個位數 (//)\n", " - 絕對值 (abs)\n", " - 四捨五入 (round)\n", "* 型別\n", " - 基本型別\n", " + int\n", " + float\n", " + str\n", " * `\"`\n", " * `'`\n", " * `\"\"\"`\n", " * `'''`\n", " * `\\` escape\n", " + tuple\n", " + list\n", " + dict\n", " + set\n", " * `|`\n", " * `&`\n", " * `^`\n", "* 輔助工具\n", " - dir\n", " - help\n", " - type\n", "* 賦值 (Assign)\n", "* 真偽值\n", " - True/False\n", " - `>` `>=` `<` `<=` `==` `!=` `in`\n", " - and/or/not\n", " - is\n", " - 各種 empty 狀況\n", " + 0, 1\n", " + \"\", \"abc\"\n", " + (,), (1, 2)\n", " + [], [1, 2]\n", " + set(), {1, 2}\n", "* 流程控制 (注意冒號和縮排)\n", " - if ... elif ... else\n", " - for ... in ...\n", " - break\n", " - continue\n", " - while ... else ...\n", "* 更多字串操作\n", " - format string\n", " - 字串串接\n", " - slice : `start:stop[:step]`\n", "* function\n", " - def\n", " - return\n", " - arguments\n", " + defaults\n", " - function call\n", "* Slice\n", " - slice(start, stop[, step])\n", " - a[0], a[-1], a[1:99:3], a[-1:-11:-2], a[::-1] (不打的話就自動帶入頭尾), range(-1, -11, -2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 練習\n", "\n", "(Home -> House Password)\n", "\n", "\n", "\n", "(Home -> Xs and Os Referee)\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# List\n", "\n", "## List Methods\n", "\n", "* list.append\n", "* list.reverse\n", "* list.sort\n", "* list.remove\n", "* list.pop\n", "* list.index\n", "* list.insert\n", "* list.count" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 3, 4]\n", "[4, 3, 2, 1]\n", "[4, 3, 2, 1, 42]\n", "[1, 2, 3, 4, 42]\n" ] } ], "source": [ "data = [1, 2, 3]\n", "data.append(4) # 加在最後面\n", "print(data)\n", "data.reverse() # 反轉\n", "print(data)\n", "data.append(42) # 加在最後面\n", "print(data)\n", "data.sort() # 排序 (小到大)\n", "print(data)" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 3, 3, 2, 1]\n" ] } ], "source": [ "data = [1, 2, 3, 3, 2, 1]\n", "data.remove(1) # 去除第一個碰到的 1\n", "print(data)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['b', 'c', 'd']\n" ] } ], "source": [ "data = ['a', 'b', 'c', 'd']\n", "data.pop(0) # 去除第 0 項\n", "print(data)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "2\n" ] } ], "source": [ "data = ['a', 'b', 'c', 'd']\n", "print(data.index('c')) # 找到位置 " ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['a', 'z', 'b', 'c', 'd']\n" ] } ], "source": [ "data = ['a', 'b', 'c', 'd']\n", "data.insert(1, 'z') # 在 index 1 放入 'z'\n", "print(data)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3\n" ] } ], "source": [ "data = [1, 2, 3, 1, 4, 1, 5]\n", "print(data.count(1)) # 計算 1 出現的次數" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## List Comprehension\n", "\n", "更方便地建立 list" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "[2, 4, 6]" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "[i*2 for i in (1, 2, 3)] # 依序從 (1, 2, 3) 裡拿資料出來,乘上 2 後放入 list" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]\n" ] } ], "source": [ "result = [i for i in range(20) if i % 2 == 0]\n", "\n", "'''\n", "result = []\n", "for i in range(20):\n", " if i % 2 == 0:\n", " result.append(i)\n", "'''\n", "\n", "print(result)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49), (8, 64), (9, 81)]\n" ] } ], "source": [ "result = [(i, i**2) for i in range(10)]\n", "print(result)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[0, 1, 1, 3, 1, 1, 6, 1, 1, 9]\n" ] } ], "source": [ "result = [i if i % 3 == 0 else 1 for i in range(10)]\n", "\n", "'''\n", "result = []\n", "for i in range(10):\n", " if i % 3 == 0:\n", " result.append(i)\n", " else:\n", " result.append(1)\n", "'''\n", "\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# More String Operations\n", "\n", "假設現在我們有字串 A 跟 B,\n", "內容分別為 \"test\" 和 \"This is a test.\"。" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": true }, "outputs": [], "source": [ "A, B = \"test\", \"This is a test.\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## A 是否是 B 的子字串" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 12, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A in B" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 把 B 用空格切割" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "['This', 'is', 'a', 'test.']" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "B.split()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## B 是以 \"This\" 開頭的?" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "B.startswith(\"This\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 找到子字串的位置" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "B.find(\"test\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 字串重複" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'testtesttest'" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A * 3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 字串連接" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'testThis is a test.'" ] }, "execution_count": 17, "metadata": {}, "output_type": "execute_result" } ], "source": [ "A + B" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 字串用特定分隔符號連接" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'test | This is a test.'" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "' | '.join([A, B])" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'a ~~~ b ~~~ c ~~~ d'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "' ~~~ '.join(['a', 'b', 'c', 'd'])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Regular Expressions\n", "\n", "玩點小遊戲 ~\n", "\n", "* [Regex Crossword](https://regexcrossword.com/)\n", "\n", "\n", "\n", "\n", "----\n", "\n", "* [PyRegex](http://www.pyregex.com/)\n", "\n", "\n", "\n", "(我們直接看上面那張 Cheat Sheet 吧 ~)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Import\n", "\n", "利用現有的工具做事情\n", "\n", "* [The Python Standard Library](https://docs.python.org/3/library/)\n", "* [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "········\n" ] } ], "source": [ "import getpass # 使用 Python 內建的 module\n", "password = getpass.getpass() # 輸入密碼\n", "username = getpass.getuser() # 取得使用者名稱" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "········\n" ] } ], "source": [ "from getpass import getpass, getuser # 指定使用 module 內的某些 function\n", "password = getpass()\n", "username = getuser()" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "········\n" ] } ], "source": [ "import getpass as g # 這邊把 \"getpass\" 這個 module 取名成 \"g\" (名字是隨便取的,正式專案不要亂命名)\n", "password = g.getpass()\n", "username = g.getuser()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 自己寫 Module\n", "\n", "我們一般寫的 Python 檔案就直接是 module,可以拿來 import。\n", "\n", "另外可以把多個 module 放在同一個資料夾,並且在資料夾內放入 `__init__.py` 就可以把整個資料夾變成 package 來使用。\n", "\n", "```\n", ".\n", "└── mypackage\n", " ├── mymodule1\n", " └── mymodule2\n", "\n", "```" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ ".group() : 03-0123456\n", ".group(0) : 03-0123456\n", ".group(1) : 03\n", ".group(2) : 0123456\n", ".group(1, 2) : ('03', '0123456')\n", ".groups() : ('03', '0123456')\n" ] } ], "source": [ "import re\n", "result = re.match('([0-9]{2})-([0-9]{7})', '03-0123456')\n", "print('.group() : {}'.format(result.group()))\n", "print('.group(0) : {}'.format(result.group(0))) # 整個 match 到的字串\n", "print('.group(1) : {}'.format(result.group(1))) # match 到的第一個子 group\n", "print('.group(2) : {}'.format(result.group(2))) # match 到的第二個子 group\n", "print('.group(1, 2) : {}'.format(result.group(1, 2))) # match 到的第一和二個子 group\n", "print('.groups() : {}'.format(result.groups())) # match 到的所有子 group" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'foo': '03', 'bar': '0123456'}\n" ] } ], "source": [ "result = re.match('(?P<foo>[0-9]{2})-(?P<bar>[0-9]{7})', '03-0123456')\n", "print(result.groupdict())" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Unpack\n", "\n", "拆解 & 打包\n", "\n", "* `*` : list\n", "* `**` : dictionary" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(1, 2, 3)\n" ] } ], "source": [ "a = (1, 2, 3)\n", "print(a)" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3\n" ] } ], "source": [ "a, b, c = (1, 2, 3)\n", "print(a, b, c)" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 [2, 3]\n" ] } ], "source": [ "a, *b = (1, 2, 3) # 把 tuple unpack,其中一部份 pack 給b\n", "print(a, b)" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false, "scrolled": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 [2, 3] 4\n" ] } ], "source": [ "a, *b, c = (1, 2, 3, 4) # 把 tuple unpack,其中一部份 pack 給b\n", "print(a, b, c)" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 [] 2\n" ] } ], "source": [ "a, *b, c = (1, 2)\n", "print(a, b, c)" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 [2, 3]\n", "a ['b', 'c', 'd']\n" ] } ], "source": [ "for a, *b in [(1, 2, 3), ('a', 'b', 'c', 'd')]: # 在 for loop 裡使用 unpack\n", " print(a, b)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3\n" ] } ], "source": [ "def f(a, b, c):\n", " print(a, b, c)\n", "\n", "data = (1, 2, 3)\n", "f(*data) # unpack data, 等同於 f(1, 2, 3)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 42 3 12\n" ] } ], "source": [ "def f(a=1, b=2, c=3, d=4):\n", " print(a, b, c, d)\n", "\n", "data = {'b': 42, 'd': 12}\n", "f(**data) # unpack data, 等同於 f(b=42, d=12)" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 2 3\n", "1 2 3 4 5\n" ] } ], "source": [ "data = (1, 2, 3)\n", "print(*data)\n", "print(*data, 4, 5) # 這行在 Python 3.5 開始支援" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0 1 [2, 3, 4]\n", "[0, 1, 2] 3 4\n" ] } ], "source": [ "a, b, *c = range(5)\n", "print(a, b, c)\n", "*a, b, c = a, b, *c # 這行在 Python 3.5 開始支援\n", "print(a, b, c)" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{1, 2, 3, 4}\n" ] } ], "source": [ "a = [1, 2, 1, 3, 1, 4]\n", "b = {*a} # 這行在 Python 3.5 開始支援,等同於 set(a)\n", "print(b)" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42\n", "('a', 'b', 123)\n", "{'y': 7, 'z': 5}\n" ] } ], "source": [ "def f(number, *args, **kwargs):\n", " print(number)\n", " print(args)\n", " print(kwargs)\n", "\n", "f(42, 'a', 'b', 123, z=5, y=7)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Misc\n", "\n", "* sorted\n", "* any\n", "* all\n", "* sum\n", "* max\n", "* min" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## sorted" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[1, 2, 4, 5, 7]\n" ] } ], "source": [ "data = (1, 5, 2, 7, 4)\n", "print(sorted(data)) # 排序" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## all & any" ] }, { "cell_type": "code", "execution_count": 38, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "True\n" ] } ], "source": [ "data = (True, 1, \"asd\")\n", "print(all(data)) # data 裡的資料是否都為真\n", "print(any(data)) # data 裡的資料是否有一為真" ] }, { "cell_type": "code", "execution_count": 39, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "False\n" ] } ], "source": [ "data = (False, 0, \"\")\n", "print(all(data)) # data 裡的資料是否都為真\n", "print(any(data)) # data 裡的資料是否有一為真" ] }, { "cell_type": "code", "execution_count": 40, "metadata": { "collapsed": false, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "True\n" ] } ], "source": [ "data = (True, 0, \"\")\n", "print(all(data)) # data 裡的資料是否都為真\n", "print(any(data)) # data 裡的資料是否有一為真" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## sum" ] }, { "cell_type": "code", "execution_count": 41, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "15\n" ] } ], "source": [ "result = sum([1, 2, 3, 4, 5])\n", "print(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## max & min" ] }, { "cell_type": "code", "execution_count": 42, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "42\n", "1\n" ] } ], "source": [ "data = [1, 42, 2, 34, 10]\n", "print(max(data))\n", "print(min(data))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 總複習\n", "\n", "* List\n", " - List Methods\n", " + list.append\n", " + list.reverse\n", " + list.sort\n", " + list.remove\n", " + list.pop\n", " + list.index\n", " + list.insert\n", " + list.count\n", "* List Comprehension\n", " - 更方便地建立 list \n", "* More String Operations\n", " - A 是否是 B 的子字串\n", " - 把 B 用空格切割\n", " - B 是以 \"This\" 開頭的?\n", " - 找到子字串的位置\n", " - 字串重複\n", " - 字串連接\n", " - 字串用特定分隔符號連接\n", "* Regular Expressions\n", "* Import\n", "* 自己寫 Module\n", "* Unpack\n", " - 拆解 & 打包\n", " - `*` : list\n", " - `**` : dictionary\n", "* Misc\n", " - sorted\n", " - any\n", " - all\n", " - sum\n", " - max\n", " - min\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# 其他還有很多還沒包含的議題 (未全部列出)\n", "\n", "## 更多 Features\n", "\n", "* decorator\n", "* metaclass\n", "* Duck Typing\n", "* Generator\n", "* is v.s. ==\n", "* zip\n", "* map\n", "* filter\n", "* reduce\n", "* partial\n", "* closure\n", "* sum\n", "* First-class function\n", "* lambda function\n", "* join\n", "* async, await\n", "* unit testing\n", "\n", "## pip - Python 套件管理\n", "\n", "安裝別人寫的程式 ~\n", "\n", "```sh\n", "$ pip search PACKAGE\n", "$ pip install PACKAGE\n", "```\n", "\n", "example :\n", "\n", "```sh\n", "$ pip search requests\n", "$ pip install requests\n", "```\n", "\n", "## Python 記憶體管理方式 (Garbage Collection)\n", "\n", "* CPython : Reference Counting\n", "* PyPy : Incremental Generational Mark-and-Sweep GC\n", "\n", "## 更多資料結構的資訊\n", "\n", "* list 適合的操作 (效率)\n", "* collections module\n", "\n", "## Python 和其他程式語言合作\n", "\n", "* ctypes (Python & C)\n", "* cffi (Python & C)" ] } ], "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.5.1" } }, "nbformat": 4, "nbformat_minor": 0 }