From 3ada4dfb6650d8b44338f003ea6e6ba5bcaaf890 Mon Sep 17 00:00:00 2001 From: victorgau Date: Wed, 3 May 2017 09:48:41 +0800 Subject: [PATCH] remove file --- ...350\250\210\346\225\231\345\255\270.ipynb" | 3983 ----------------- 1 file changed, 3983 deletions(-) delete mode 100644 "Python \347\250\213\345\274\217\350\250\255\350\250\210\346\225\231\345\255\270.ipynb" diff --git "a/Python \347\250\213\345\274\217\350\250\255\350\250\210\346\225\231\345\255\270.ipynb" "b/Python \347\250\213\345\274\217\350\250\255\350\250\210\346\225\231\345\255\270.ipynb" deleted file mode 100644 index d18b8e2..0000000 --- "a/Python \347\250\213\345\274\217\350\250\255\350\250\210\346\225\231\345\255\270.ipynb" +++ /dev/null @@ -1,3983 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "904e7041-5347-4036-bfff-4b5af4763913" - }, - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 程式設計教學\n", - "\n", - "## Victor Gau\n", - "\n", - "### [victorgau@gmail.com](\"mailto:victorgau@gmail.com?subject=[Question]QF20170311\")\n", - "\n", - "### 2017-03-11\n", - "\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "## Prerequisites:\n", - "\n", - "* 安裝 Anaconda:[https://www.continuum.io/downloads](https://www.continuum.io/downloads)\n", - "\n", - "\n", - "* 安裝 jupyter notebook 的 [RISE 套件](https://github.com/damianavila/RISE)\n", - "```\n", - "c:\\> conda install -c damianavila82 rise\n", - "```\n", - "\n", - "* 下載教材:[https://github.com/victorgau/QF20170311](https://github.com/victorgau/QF20170311)\n", - "\n", - "\n", - "* 啟動 jupyter notebook\n", - "```\n", - "c:\\> jupyter notebook\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "## 大綱\n", - "\n", - "* Python 簡介\n", - "* Python 安裝及使用\n", - "* Python 的變數\n", - "* Python 資料型態:int, float, str, bool, datetime\n", - "* Python 容器型別:list, tuple, dict, set\n", - "* Python 的運算子\n", - "* Python 流程控制:if statement, loops\n", - "* Python 函式\n", - "* Python 生成式 (Comprehension)\n", - "* Python 檔案IO\n", - "* Python 網路資料存取\n", - "* Python 例外處理\n", - "* Python 物件導向設計\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 簡介" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Python 之父\n", - "### Guido Van Rossum (荷蘭, 1956~)\n", - "\n", - "[![Guido Van Rossum (荷蘭, 1956~)](images/Guido_van_Rossum_OSCON_2006_cropped.png)](https://en.wikipedia.org/wiki/Guido_van_Rossum)\n", - "\n", - "* 1989 年 Xmas 時,為了打發時間,Guido 開始寫 Python。\n", - "* 1991 釋出 Python。\n", - "* 取名 Python 的原因是 Guido 喜歡看 \"Monty Python's Flying Circus\"。\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "293af2dd-d2e0-4f2e-a448-2cbf1641e7d5" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Why Python?\n", - "\n", - "* 自由軟體:完全免費、參與者眾\n", - "* 擴充性強:模組豐富、應用性強\n", - "* 易學好用:語法簡潔、易學易懂\n", - "* 跨平台:Windows / Linux / Mac / ...\n", - "* 同好者眾:支援性強、問題快解\n", - "\n", - "[More:Python 發展歷史與特點](http://www.ziqiangxuetang.com/python/python-intro.html)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 從下面的笑話,可以稍微看出 Python 的特點!\n", - "\n", - "![](images/python-vs-java.jpg)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Python is a glue language!!!\n", - "\n", - "* 使用者通常不需要自己實作程式所有的功能,而是需要協調及整合模組跟套件的運作!!!\n", - "\n", - "|| C/C++ | Python |\n", - "|:-:|:-:|:-:|\n", - "|開發速度|慢|快|\n", - "|偵錯速度|慢|快|\n", - "|佈署速度|慢|快|\n", - "|執行速度|非常快|快|\n", - "\n", - "* 使用 Python 可以在最短的時間做出產品雛形。" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 新創公司喜歡 Python!\n", - "\n", - "[![](images/AL_jobs.png)](https://www.codementor.io/learn-programming/beginner-programming-language-job-salary-community)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 學校喜歡教 Python (Top US Universities Teach Python)\n", - "\n", - "[![](images/Top39-700.4.png)](http://cacm.acm.org/blogs/blog-cacm/176450-python-is-now-the-most-popular-introductory-teaching-language-at-top-u-s-universities/fulltext)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 初學者喜歡學 Python (PYPL, PopularitY of Programming Language Index)\n", - "\n", - "[![](images/PYPL_2017_03.png)](http://pypl.github.io/PYPL.html)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "81f50645-13d2-43a5-a557-902be09c9968" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 電子電機工程師喜歡 Python (2016 IEEE Programming Languages Ranking)\n", - "[![](images/2016 IEEE Top 10 Programming Languages.png)](http://spectrum.ieee.org/computing/software/the-2016-top-programming-languages)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "[![](images/IoT_languages.png)](http://www.developer-tech.com/news/2016/apr/20/research-iot-developer-survey-reveals-popular-technologies/)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 資料科學家喜歡 Python (Top 10 Tools for Analytics/Data Science)\n", - "\n", - "[![](images/top10-analytics-data-science-software-2016.jpg)](http://www.kdnuggets.com/2016/06/r-python-top-analytics-data-mining-data-science-software.html)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 社群喜歡 Python (TIOBE Programming Community Index)\n", - "\n", - "[![](images/Tiobe_2017_02.png)](http://www.tiobe.com/tiobe-index/)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 後端喜歡 Python (Python/Django Market Share)\n", - "\n", - "[![](images/silicon_valley.png)](https://www.quora.com/How-is-the-market-for-programmers-in-Python-Django)\n", - "\n", - "[![](images/berlin.png)](https://www.quora.com/How-is-the-market-for-programmers-in-Python-Django)\n", - "\n", - "[![](images/barcelona.png)](https://www.quora.com/How-is-the-market-for-programmers-in-Python-Django)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "[![](images/backend.png)](https://en.wikipedia.org/wiki/Programming_languages_used_in_most_popular_websites)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Fintech 喜歡 Python\n", - "[![](images/fintech-finance-1.png)](https://blog.hackerrank.com/emerging-languages-still-overshadowed-by-incumbents-java-python-in-coding-interviews/)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "25ac7855-2c20-47bb-b4ab-6a7fbba20e2d" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 2015 Github Statistics\n", - "[![](images/Python vs R in Github.png)](http://githut.info/?utm_content=buffer781de&utm_medium=social&utm_source=facebook.com&utm_campaign=buffer)\n", - "\n", - "[Python vs. R (Datacamp)](https://www.datacamp.com/community/tutorials/r-or-python-for-data-analysis)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "6ddd881a-45b7-47cb-8a82-8c8280270623" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## stackoverflow\n", - "[![](images/2016 stackoverflow Languages Ranking.png)](http://stackoverflow.com/research/developer-survey-2016#technology-most-popular-technologies)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 天瓏書局中文暢銷書排行榜\n", - "\n", - "|月份|前五名 Python 書籍有幾本?|前十名 Python 書籍有幾本?|\n", - "|:----:|:----------------------:|:----------------------:|\n", - "|[2016/09](https://www.tenlong.com.tw/zh_tw/bestselling?date=2016-09-30)|2|3|\n", - "|[2016/10](https://www.tenlong.com.tw/zh_tw/bestselling?date=2016-10-30)|3|5|\n", - "|[2016/11](https://www.tenlong.com.tw/zh_tw/bestselling?date=2016-11-30)|4|5|\n", - "|[2016/12](https://www.tenlong.com.tw/zh_tw/bestselling?date=2016-12-28)|4|6|\n", - "|[2017/01](https://www.tenlong.com.tw/zh_tw/bestselling?date=2017-01-28)|3|6|\n", - "|[2017/02](https://www.tenlong.com.tw/zh_tw/bestselling?date=2017-02-28)|4|6|" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Python -> 工程師最佳第二程式語言" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## So... Python 2 or 3 ?..." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 注意:\n", - "* Python 3 主要針對了 Python 的 Unicode 的部分做了修正,解決了很多處理字元編碼的問題,但也破壞了向後相容性。\n", - "* Python 2.7 是 Python 2 的最後一個版本,預計只支援到 2020 年。\n", - "* Python 2.7 版只會對臭蟲跟安全問題做修正,不會再增加新功能。\n", - "* 常用的套件,大部分都已經遷移到 Python 3 上。" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "[![](images/py3readiness.png)](http://py3readiness.org/)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 建議安裝 Python 3.x!!!\n", - "\n", - "### (本課程使用 Python 3.5)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 安裝及使用" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "3fa64452-39b2-4e24-983d-07a5bf82b02e" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Python 環境建置:Anaconda (推薦)\n", - "\n", - "* 版本:2.x vs. 3.x\n", - "\n", - "[![](images/Anaconda.png)](https://www.continuum.io/downloads)\n", - "\n", - "[More](http://www.ziqiangxuetang.com/python/python-install.html)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 使用 conda 安裝套件\n", - "\n", - "* 檢查 conda 的版本\n", - "```\n", - "c:\\> conda -V\n", - "```\n", - "\n", - "* 更新 conda\n", - "```\n", - "c:\\> conda update conda\n", - "```\n", - "\n", - "* 安裝 package\n", - "```\n", - "c:\\> conda install -n yourenvname [package]\n", - "# 注意:如果沒有加 \"-n yourenvname\",則套件會被安裝到 root env\n", - "```\n", - "\n", - "* 移除 package\n", - "```\n", - "c:\\> conda uninstall -n yourenvname [package]\n", - "```\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 使用 conda 建立 Virtual Environment\n", - "\n", - "\n", - "* 建立 virtual environment\n", - "```\n", - "c:\\> conda create -n yourenvname python=x.x anaconda\n", - "```\n", - "\n", - "* 列出所有 virtual environment\n", - "```\n", - "c:\\> conda info -e\n", - "```\n", - "\n", - "* 啟動 virtual environment\n", - "```\n", - "c:\\> source activate yourenvname\n", - "```\n", - "\n", - "* 停止 virtual environment\n", - "```\n", - "c:\\> source deactivate\n", - "```\n", - "\n", - "* 刪除 virtual environment\n", - "```\n", - "c:\\> conda remove -n yourenvname --all\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Hello World\n", - "\n", - "* 打開 notepad\n", - "* 鍵入 \"print(\"Hello World!\")\"\n", - "* 存成 hello.py 檔!\n", - "* 在命令列使用 python hello.py 執行!\n", - "```\n", - "c:\\> python hello.py\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "# Python 的程式架構" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "![](images/Python_Syntax.png)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## 重點:\n", - "\n", - "* Python 使用空白字元來定義程式結構\n", - " - 每一行最前面的空白字元的數目是有意義的\n", - " - 同一個區塊的縮排需要一樣\n", - "* 使用 import 來載入套件或模組\n", - "* \"#\" 開頭的為註解\n", - "* 引號(單引號或雙引號)標注起來的為字串" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 怎麼尋找 Python 套件?" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "94a40ef6-d5f5-451d-ba73-d11f8d4b2719" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## PyPI (Python Packages Index)\n", - "[![](images/PyPI.png)](https://pypi.python.org/pypi)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 如何安裝套件?" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## [使用 pip](https://pip.pypa.io/en/stable/)\n", - "\n", - "* 安裝套件\n", - "```\n", - "c:\\> pip install \n", - "```\n", - "\n", - "* 更新套件\n", - "```\n", - "c:\\> pip install --upgrade \n", - "```\n", - "\n", - "* 移除套件\n", - "```\n", - "c:\\> pip uninstall \n", - "```\n", - "\n", - "* 搜尋套件\n", - "```\n", - "c:\\> pip search \n", - "```\n", - "\n", - "* 列出已安裝套件\n", - "```\n", - "c:\\> pip list\n", - "```\n", - "\n", - "* 列出已安裝套件 (requirement format)\n", - "```\n", - "c:\\> pip freeze\n", - "```\n", - "\n", - "* 將已安裝之套件及版本輸出成文字檔\n", - "```\n", - "c:\\ pip freeze > requirements.txt\n", - "```\n", - "\n", - "* 從 requirements.txt 安裝對應套件\n", - "```\n", - "c:\\ pip install -r requirements.txt\n", - "```" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Python 的IDE\n", - "\n", - "* [Atom](https://atom.io/)\n", - "* [PyCharm Community Edition](https://www.jetbrains.com/pycharm/download/)\n", - "* [Sublime Text](https://www.sublimetext.com/)\n", - "* [Visual Studio Code](https://code.visualstudio.com/)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "72048d63-6776-41b6-874e-5ef962c3246a" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Python IDE: Spyder (Anaconda 內建)\n", - "![](images/SpyderIDE.png)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "28a11fcd-516d-4007-ae51-4304d199cfbc" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## Python IDE: jupyter notebook (Anaconda 內建)\n", - "* jupyter 由來:[julia](http://julialang.org/) + [Python](https://www.python.org/) + [R](https://www.r-project.org/)\n", - "* 互動式、即見式、展演式\n", - "[![](images/jupyter.png)](http://jupyter.org/)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "nbpresent": { - "id": "e9d95b93-a13a-4adc-9aad-51e724a8e75b" - }, - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## jupyter notebook 基礎常識\n", - "\n", - "* 啟動 jupyter notebook\n", - " - 程式集:搜尋 jupyter notebook => 左鍵點擊 jupyter notebook\n", - " - 終端機 (命令提示字元):輸入 jupyter notebook\n", - "\n", - "* [27 Jupyter Notebook tips, tricks and shortcuts](https://www.dataquest.io/blog/jupyter-notebook-tips-tricks-shortcuts/) ([中譯版](http://www.liuchengxu.org/pelican-blog/jupyter-notebook-tips.html))" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 常用的熱鍵或指令\n", - "* 執行區塊:\n", - " - Shfit + Enter 執行該 cell 且跳下一個 cell\n", - " - Ctrl + Enter 執行該 cell (但停在該 cell)\n", - "* 自動填滿:Tab 鍵\n", - "* 提示引數:Shift + Tab\n", - "* 線上諮詢:\n", - " - ?FunctionName()\n", - " - help FunctionName\n", - "* 註解:\n", - " - 單行註解 #\n", - " - 多行註解 ''' '''\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 魔術命令 (Magic Commands) 清單\n", - "%lsmagic" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 的模組及套件" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 什麼是模組?\n", - "\n", - "* 每個 .py 的檔案就是一個模組\n", - "* 模組可以被直接執行,也可以被載入其他模組內執行\n", - "* 每個模組有一個特殊屬性: \"\\_\\_name\\_\\_\"\n", - " - 如果模組被直接執行,\"\\_\\_name\\_\\_\"屬性的值為\"\\_\\_main\\_\\_\"。\n", - " - 如果被載入其他模組,\"\\_\\_name\\_\\_\"屬性的值為自己的模組名稱。" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 什麼是套件?\n", - "\n", - "* 套件為用來管理模組的目錄架構。\n", - "* 每個套件目錄底下,必須有一個名為\"\\_\\_init\\_\\_.py\"的檔案。" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 套件範例:\n", - "\n", - "![](images/package.png)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 怎麼載入模組及套件?\n", - "\n", - "* import\n", - "* import... as...\n", - "* from... import..." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# Python 的模組搜尋路徑\n", - "\n", - "import sys\n", - "\n", - "sys.path" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 如果要使用的模組所在的目錄,不在搜尋的路徑上,可以使用下面方式加入\n", - "\n", - "# 1.\n", - "# sys.path.append(r\"c:\\path\\to\\the\\module\")\n", - "\n", - "# 2.\n", - "# 也可以設定 PYTHONPATH 參數,讓 Python 去搜尋特定路徑\n", - "\n", - "# 3.\n", - "# 設定一個 .pth 檔,將 .pth 檔放在 package 的存放路徑上,.pth 檔裡面填入模組的路徑" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "import site\n", - "\n", - "site.getsitepackages()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 的變數" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 變數的命名規則\n", - "\n", - "* 變數名稱最好以英文字母或底線做開頭 (數字不能做開頭)\n", - " - \\_variable, variable, variable\\_ \n", - "* 除開頭字元外,其他字元使用數字、底線、或英文字母\n", - " - _var123, var_123\n", - "* 變數會區分大小寫\n", - "* 避開 keywords\n", - "* 避開 [built-in objects](https://docs.python.org/3/library/builtins.html)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "字串 = \"Hello World!\"\n", - "\n", - "print(字串)\n", - "\n", - "# 咦... 可以用中文變數耶!!!\n", - "\n", - "# 但是請不要這樣用,因為在使用很多套件時,這樣的變數名稱可能會造成問題。" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "import string\n", - "\n", - "# help(string)\n", - "\n", - "# ?string\n", - "\n", - "string.ascii_letters" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# Keywords\n", - "\n", - "import keyword\n", - "\n", - "print(keyword.kwlist)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# https://docs.python.org/3/reference/executionmodel.html\n", - "\n", - "# built-in objects\n", - "\n", - "# Python 2.7.x\n", - "#import __builtin__\n", - "#\n", - "#dir(__builtin__)\n", - "\n", - "# Python 3.5\n", - "\n", - "import builtins\n", - "\n", - "print(dir(builtins))" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 兩個好用的函數:\n", - "\n", - "* type()\n", - "* dir()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 使用 type() 列出變數型別\n", - "\n", - "a = 1\n", - "\n", - "type(a)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "b = '123'\n", - "\n", - "type(b)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 使用 dir() 列出 local scope 裡面有那些變數或模組等\n", - "dir()\n", - "\n", - "# 關於 magic methods\n", - "# http://minhhh.github.io/posts/a-guide-to-pythons-magic-methods" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 使用 dir(module) 列出模組可以使用的屬性及方法等\n", - "\n", - "dir(sys)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 使用 dir() 列出物件的方法及屬性\n", - "\n", - "print(dir(b))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "c = [1, 2, 3]\n", - "\n", - "type(c)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "print(dir(c))" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 的資料型態" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 資料型態\n", - "* 數值 number\n", - " - 整數 integer (int)\n", - " - 浮點數 float\n", - " - 複數 (complex)\n", - "* 字串 string (str)\n", - "* 布林 boolean (bool)\n", - "* 日期時間 datetime\n", - "* None" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 整數 int\n", - "A = 3\n", - "type(A)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "B = 2\n", - "C = A + B\n", - "type(C)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 2進位 (0b), 8進位 (0o), 16進位 (0x) 整數\n", - "A = 0b101\n", - "type(A)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "A" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "A = 0xFF\n", - "A" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 型別轉換\n", - "\n", - "# 字串轉整數\n", - "A='10'\n", - "type(A)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "B=int(A)\n", - "type(B)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "B" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 無前綴時,將字串轉乘 8 進位整數\n", - "int('12', 8)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 有前綴時,將字串轉乘 8 進位整數\n", - "int('0o12', 0)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 浮點數轉整數\n", - "int(3.6)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 整數轉成不同進位的字串\n", - "oct(10)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "hex(10)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 浮點數 float\n", - "A = 1.23\n", - "type(A)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 浮點數另一種表示法\n", - "B = 1E-3\n", - "B" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "C = 2\n", - "type(C)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "D = B + C\n", - "type(D)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 字串 str\n", - "\n", - "# 字串宣告\n", - "Name = 'Victor'\n", - "type(Name)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "ID = '001'\n", - "\n", - "## 字串串聯 (相加)\n", - "NameID = Name + ID\n", - "NameID" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "skip" - } - }, - "outputs": [], - "source": [ - "# 跳脫字元?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "## 字串分割\n", - "sentence = 'It is raining cats and dogs'\n", - "words = sentence.split(' ') # 注意:此處是 ' ' 而非 ''\n", - "print(words)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 格式化輸出\n", - "\n", - "## 傳統作法 I\n", - "print('Name=' + Name + ': A=' + str(A) + '; B=' + str(B))\n", - "\n", - "## 傳統作法 II\n", - "print('Name=%s: A=%d; B=%d' % (Name, A, B))\n", - "print('Name=%s: A=%d; B=%f' % (Name, A, B))\n", - "print('Name=%s: A=%d; B=%3.5f' % (Name, A, B))\n", - "\n", - "''' \n", - "%d is the format code for an integer.\n", - "%f is the format code for a float.\n", - "%s prints the str() of an object\n", - "%r prints the repr() of an object (\n", - "'''\n", - "# http://stackoverflow.com/questions/15215242/python-2-7-d-s-and-float" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "## 建議作法\n", - "print('Name={0}: A={1}; B={2}'.format(Name, A, B))\n", - "print('Name={}: A={}; B={}'.format(Name, A, B))" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 什麼是 Unicode?\n", - "\n", - "* [Wikipedia - Unicode](https://en.wikipedia.org/wiki/Unicode)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "fragment" - } - }, - "source": [ - "### 什麼是 Encode()?\n", - "\n", - "將字串轉換成特定格式(如UTF-8)的 bytes,以便於儲存或網路傳輸。 " - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "fragment" - } - }, - "source": [ - "### 什麼是 Decode()?\n", - "\n", - "將特定格式的 bytes,轉換回字串以便於顯示。" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "a = \"中文\"\n", - "b = a.encode('utf-8')\n", - "b" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "type(b)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "b.decode('utf-8')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 從字元找對應的 codepoint\n", - "ord('中')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 從 codepoint 找回字元\n", - "chr(20013)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "hex(ord('中'))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 邏輯 bool: True: 1; False: 0\n", - "\n", - "A = 3\n", - "B = 3\n", - "\n", - "A == B\n", - "type(A == B)\n", - "A != B\n", - "\n", - "A is B\n", - "A is not B\n", - "\n", - "res = (A == B)\n", - "res\n", - "res == 0" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# datetime\n", - "#\n", - "# package: datetime\n", - "# http://www.wklken.me/posts/2015/03/03/python-base-datetime.html\n", - "\n", - "# 取得當下的日期與時間\n", - "import datetime" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "now = datetime.datetime.now()\n", - "now" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "type(now) # datetime.datetime" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "datetime.datetime.now().date()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "type(datetime.datetime.now().date()) # datetime.date" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "datetime.datetime.now().time()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "type(datetime.datetime.now().time()) # datetime.time" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "datetime.date.today()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "type(datetime.date.today()) " - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 1. 字串 -> 日期\n", - "# 2. 日期 -> 字串\n", - "\n", - "# https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior\n", - "\n", - "# strptime\n", - "s = '2017-03-11'\n", - "datetime.datetime.strptime(s, '%Y-%m-%d')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# datetime 2 string: .strftime(Format)\n", - "date = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n", - "date" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "date = datetime.datetime.now().strftime(\"%Y%m%d\")\n", - "date" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 的容器類別" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 容器類別 (資料結構)\n", - "* [列表 list](http://www.runoob.com/python/python-lists.html)\n", - "* [元組 tuple](http://www.runoob.com/python/python-tuples.html)\n", - "* [字典 dict](http://www.runoob.com/python/python-dictionary.html)\n", - "* [集合 set](http://www.iplaypython.com/jichu/set.html)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 列表 list:[]\n", - "\n", - "## 宣告方式\n", - "list1 = []\n", - "list1 = list()\n", - "type(list1)\n", - "\n", - "list1 = ['B', 'A', 'C'] \n", - "list1\n", - "\n", - "# indexing 索引指標\n", - "list1[0] \n", - "list1[-1]\n", - "\n", - "# slicing\n", - "list1[1:]\n", - "\n", - "# len():計算 list 長度\n", - "len(list1) \n", - "\n", - "list2 = [80, 70]\n", - "\n", - "# list 串聯\n", - "list1 + list2\n", - "\n", - "# list 複製\n", - "list1 * 3" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "a = [1, 2, 3]" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "a" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "a * 2" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "b = np.array([1, 2, 3])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "b" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "b * 2" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "## in 隸屬 (包含) operatior\n", - "element = 'C'\n", - "element in list1\n", - "\n", - "element = 'D'\n", - "element in list1\n", - "\n", - "## 排序:sorted()\n", - "sorted(list1)\n", - "sorted(list1, reverse=True)\n", - "\n", - "## 排序:.sort() # 注意:會蓋掉原始序列\n", - "list3 = list1.copy() \n", - "print(list3)\n", - "\n", - "list3.sort()\n", - "print(list3)\n", - "\n", - "list3.sort(reverse=True)\n", - "print(list3)\n", - "\n", - "## 顛倒 list\n", - "list3.reverse()\n", - "print(list3)\n", - "\n", - "## 移除特定 element\n", - "list3.remove('B')\n", - "print(list3)\n", - "\n", - "## 刪除 list\n", - "del list3" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# tuple 元組:()\n", - "\n", - "## tuple vs. list: \n", - "# 1. tuple 生成後不可修改;list 生成後可以修改 (區別:記憶體能否動態配置)\n", - "# 2. tuple 的處理效能會優於 list,但 list 的彈性會優於 tuple\n", - "\n", - "## 宣告方式\n", - "tup1 = ()\n", - "tup1 = tuple()\n", - "type(tup1)\n", - "\n", - "tup1 = ('physics', 'chemistry', 1997, 2000)\n", - "tup1\n", - "\n", - "# 型別轉換\n", - "tuple(list1) # list 2 tuple\n", - "list(tup1) # tuple 2 list" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# dict 字典:{key : value}\n", - "\n", - "## 宣告 dict\n", - "dict1 = {}\n", - "type(dict1)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "dir(dict)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "dict1 = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}\n", - "dict1" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "dict1.keys()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "dict1.values()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "dict1.items()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "dict1['Alice']" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# set 集合\n", - "\n", - "# 宣告 set\n", - "set1 = set()\n", - "type(set1)\n", - "\n", - "a = set('abc')\n", - "a.add('wxyz')\n", - "a\n", - "\n", - "a = set('abc')\n", - "a.update('wxyz')\n", - "a\n", - "\n", - "a = set('abc')\n", - "b = set('cde')\n", - "a & b # 交集\n", - "a | b # 聯集\n", - "a - b # 差集" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 的運算子" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 重點:\n", - "\n", - "* 算術運算子\n", - "* 比較運算子\n", - "* 指定運算子\n", - "* 邏輯運算子\n", - "* 位元運算子\n", - "* 成員運算子 (in, not in)\n", - "* 相等運算子 (Identity Operator) (is, is not)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 算術運算子\n", - "\n", - "|運算子|說明|\n", - "|:-:|:-:|\n", - "|+|加法|\n", - "|-|減法|\n", - "|\\*|乘法|\n", - "|/|除法|\n", - "|//|整數除法|\n", - "|**|次方|\n", - "|%|求餘數|" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 比較運算子\n", - "\n", - "|運算子|說明|\n", - "|:-:|:-:|\n", - "|==|等於|\n", - "|!=|不等於|\n", - "|>|大於|\n", - "|<|小於|\n", - "|>=|大於等於|\n", - "|<=|小於等於|" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 指定運算子\n", - "\n", - "|運算子|範例|同義式|\n", - "|:-:|:-:|::|\n", - "|=|a = b||\n", - "|+=|a += b|a = a + b|\n", - "|-=|a -= b|a = a - b|\n", - "|\\*=|a \\*= b|a = a \\* b|\n", - "|/=|a /= b|a = a / b|\n", - "|%=|a %= b|a = a % b|\n", - "|**=|a **= b|a = a ** b|\n", - "|//=|a //= b|a = a // b|" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 邏輯運算子 (Logical Operators)\n", - "\n", - "|運算子|說明|\n", - "|:-:|:-:|\n", - "|and|且|\n", - "|or|或|\n", - "|not|非|" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "a = True\n", - "b = False\n", - "c = True\n", - "\n", - "a and b" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "a and c" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "a or c" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "not (a and b)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 成員運算子 (Membership Operators)\n", - "\n", - "|運算子|說明|\n", - "|:-:|:-:|\n", - "|in|在容器類別中|\n", - "|not in|不在容器類別中|" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "a = [1, 2, 3]\n", - "\n", - "1 in a" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "4 in a" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 位元運算子 (Bitwise Operators)\n", - "\n", - "|運算子|說明|\n", - "|:-:|:-:|\n", - "|&|邏輯 and|\n", - "|||邏輯 or|\n", - "|^|邏輯 xor|\n", - "|~|邏輯 not|\n", - "|>>|位元右移|\n", - "|<<|位元左移|" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 相等預算子 (Identity Operators)\n", - "\n", - "會比較兩變數的記憶體位置是否相等。\n", - "\n", - "|運算子|說明|\n", - "|:-:|:-:|\n", - "|is|物件相等|\n", - "|is not|物件不相等|" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 流程控制" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 重點:\n", - "\n", - "* if 語句\n", - " - if\n", - " - if-else\n", - " - if-elif-else\n", - "* 迴圈\n", - " - for loop\n", - " - while loop\n", - " - continue, break,..." - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 條件判斷 if\n", - "name = \"Victor\"\n", - "\n", - "if name == \"Victor\":\n", - " print(\"Hi!\", name)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 條件判斷 if-else\n", - "\n", - "A = 3\n", - "B = 2\n", - "\n", - "if A == B:\n", - " print('A = B')\n", - "else:\n", - " print('A != B')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 條件判斷 if-elif-else\n", - "\n", - "A = 3\n", - "B = 2\n", - "\n", - "if A > B:\n", - " print('A > B')\n", - "elif A < B:\n", - " print('A < B')\n", - "else:\n", - " print('A = B')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# for 迴圈\n", - "\n", - "A = range(10)\n", - "\n", - "for i in A:\n", - " print('{} \\n'.format(i))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "help(range)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# for 迴圈\n", - "\n", - "A = range(1,10, 2)\n", - "\n", - "for i, item in enumerate(A): # enumerate: iterator\n", - " print('{}: {} \\n'.format(i, item))" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# while 迴圈\n", - "\n", - "count = 0\n", - "while (count < 8):\n", - " print(count)\n", - " count += 1" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# while 迴圈\n", - "\n", - "count = 0\n", - "while (count < 8):\n", - " count += 1\n", - " if count % 2 == 0:\n", - " continue\n", - " print(count)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# while 迴圈\n", - "\n", - "count = 0\n", - "while (count < 8):\n", - " count += 1\n", - " if count % 2 == 0:\n", - " break\n", - " print(count)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# while 迴圈\n", - "\n", - "count = 0\n", - "while (count < 10):\n", - " if count % 3 == 0:\n", - " print(str(count))\n", - " count += 1" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 函式" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 函式 (Functions)\n", - "\n", - "* 使用 def 定義函式\n", - "* pass\n", - "* lambda function (匿名函式)\n", - "* 位置引數 (positional arguments)\n", - "* 關鍵字引數 (keyword arguments)\n", - "* 預設引數 (default arguments)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 函式定義\n", - "def f():\n", - " print(\"Hello!\")\n", - "\n", - "# 函式呼叫\n", - "f()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 空函式\n", - "def f():\n", - " pass\n", - "\n", - "f()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# def function\n", - "def f(x): \n", - " return x**2\n", - "\n", - "def f(x): return x**2\n", - "\n", - "# lambda function\n", - "g = lambda x: x**2\n", - "\n", - "f(3)\n", - "g(3)\n", - "\n", - "MySum = lambda x, y: x + y\n", - "MySum(3,2)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "## 字串分割\n", - "sentence = 'It is raining cats and dogs'\n", - "words = sentence.split(' ') # 注意:此處是 ' ' 而非 ''\n", - "type(words)\n", - "print(words)\n", - "\n", - "lengths = map(lambda word: len(word), words)\n", - "print(lengths)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# function\n", - "\n", - "def MyMean(data):\n", - " total = 0\n", - " for num in data: # 避免使用回圈是提高計算效率的關鍵之一\n", - " total = total + num\n", - " return total / len(data)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "data = [1, 2, 5, 8, 11]\n", - "MyMean(data)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# Positional Parameters\n", - "def f(a, b, c):\n", - " return {'a':a, 'b':b, 'c':c}\n", - "\n", - "f(1, 2, 3)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# Keyword Parameters\n", - "def f(a, b, c):\n", - " return {'a':a, 'b':b, 'c':c}\n", - "\n", - "f(b=1, c=2, a=3)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "f(1, c=2, b=3)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# * 跟 ** 的使用\n", - "def f(*args):\n", - " print(args)\n", - "\n", - "f(1, 2, 3, 4)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "def f(**kwargs):\n", - " print(kwargs)\n", - " \n", - "f(a=1, b=2, c=3)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "def f(*args, **kwargs):\n", - " print(\"args:\", args)\n", - " print(\"kwargs:\", kwargs)\n", - " \n", - "f(1, 2, 3)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# unpacking\n", - "\n", - "arg_dict = {'a':1, 'b':2, 'c':3}\n", - "\n", - "f(**arg_dict)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "# default arguments?" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "# decorator?" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 生成式 (Comprehension)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 重點:\n", - "\n", - "* list comprehension\n", - "* dict comprehension\n", - "* set comprehension\n", - "* generator comprehension" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# list comprehension\n", - "a = [1, 2, 3]\n", - "b = [e**2 for e in a]\n", - "b" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# dict comprehension\n", - "word = \"letters\"\n", - "letter_counts = {letter: word.count(letter) for letter in word}\n", - "letter_counts" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# set comprehension\n", - "a_set = {number for number in range(1, 6) if number % 3 == 1}\n", - "a_set" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# generator comprehension\n", - "a = [1, 2, 3]\n", - "b = (e**2 for e in a)\n", - "b" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "for c in b:\n", - " print(c)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 的檔案IO" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 常見的儲存方式\n", - "* 文字檔:txt (tab 分隔 / space 分隔)、csv (逗點分隔)\n", - "* EXCEL 檔:xls / xlsx\n", - "* 網路檔:html / xml / json\n", - "* 資料庫:SQLite / PostgreSQL / MySQL..." - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 一般文字檔" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 寫入檔案\n", - "file = open('test.txt','w')\n", - "file.write('this is a test!')\n", - "file.close()" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### mode 字串\n", - "|字元|說明|\n", - "|:-:|:-|\n", - "|r|讀取模式|\n", - "|w|寫入模式|\n", - "|x|檔案不存在時才寫入|\n", - "|a|附加模式|\n", - "|b|二進位模式|\n", - "|t|文字模式|\n", - "|+|更新模式|" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 讀取檔案:\n", - "file = open('test.txt', 'r')\n", - "# 把所有資料一次全部讀進來\n", - "text = file.read()\n", - "\n", - "print(text)\n", - "# 關閉檔案\n", - "file.close()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 讀取檔案:\n", - "# 如果沒有第二個參數,表示預設的模式是 'r'\n", - "file = open('test.txt')\n", - "\n", - "# 一次全部讀進來,但是分行\n", - "text = file.readlines()\n", - "\n", - "print(text)\n", - "\n", - "# 關閉檔案\n", - "file.close()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 讀取檔案:\n", - "file = open('test.txt')\n", - "\n", - "# 將資料一行一行的讀進來處理\n", - "for line in file:\n", - " print(line)\n", - "\n", - "# 關閉檔案\n", - "file.close()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 附加資料 (Append)\n", - "file = open('test.txt', 'a')\n", - "file.write('this is a test!')\n", - "file.close()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 如果不想每一次都要呼叫 close() 來關閉檔案,則可以使用 with … as 語法。\n", - "with open('test.txt') as file:\n", - " text = file.read()\n", - " print(text)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### .csv 檔\n", - "\n", - "### csv 是 Comma Separated Values 的縮寫" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "import csv" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 台灣證券交易所 - 加權指數歷史資料\n", - "# http://www.tse.com.tw/ch/trading/indices/MI_5MINS_HIST/MI_5MINS_HIST.php#\n", - "# 此範例取自 \"Python 3.5 技術手冊, 林信良\"\n", - "with open('MI_5MINS_HIST10603.csv', encoding='Big5') as f:\n", - " for row in csv.reader(f):\n", - " print(row)" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "with open('MI_5MINS_HIST10603.csv', encoding='Big5') as rf:\n", - " with open('10603-UTF8.csv', 'w', encoding='UTF-8', newline='') as wf:\n", - " rows = csv.reader(rf)\n", - " csv.writer(wf).writerows(rows)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# Python 的網路資料擷取" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 重點:\n", - "\n", - "* 怎麼使用 requests 擷取網路資料?\n", - "* 處理 json 資料\n", - "* 處理 html 資料" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "import requests\n", - "import json" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "r=requests.get('http://cloud.culture.tw/frontsite/trans/SearchShowAction.do?method=doFindAllTypeJ')\n", - "r.text" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 載入 json 檔案\n", - "doc=json.loads(r.text)\n", - "print(doc[0]['categoryName'])" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true - }, - "outputs": [], - "source": [ - "dict1 = {'a':1, 'b':2, 'c':3}" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "doc1 = str(dict1)\n", - "doc1" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false - }, - "outputs": [], - "source": [ - "doc2 = json.dumps(dict1)\n", - "doc2" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "\n", - "# Python 的例外處理" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "### 重點:\n", - "\n", - "* try... except\n", - "* try... except... else\n", - "* try... except... else... finally" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "a = 1\n", - "b = 0\n", - "a / b" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 如果知道可能產生的錯誤是甚麼\n", - "\n", - "try:\n", - " a / b\n", - "except ZeroDivisionError:\n", - " print(\"哇!除數是零!\")" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "import sys\n", - "\n", - "try:\n", - " a / b\n", - "except:\n", - " print(sys.exc_info())" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "slide" - } - }, - "source": [ - "# 物件導向設計\n", - "## (Object-Orientation Programming, OOP)" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 注意:\n", - "\n", - "* 解決問題並不一定需要使用物件導向設計。\n", - "* 雖然在 Python 中,萬物皆為物件!但Python之父 Guido van Rossum 曾經說過,自己並非物件導向的信徒。" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 物件導向設計的三大核心觀念:\n", - "\n", - "* 封裝 (Encapulation)\n", - "* 繼承 (Inheritance)\n", - "* 多型 (Polymorphism)\n" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "slideshow": { - "slide_type": "subslide" - } - }, - "source": [ - "## 重點:\n", - "\n", - "* 怎麼定義類別?\n", - "* 生成物件 (Instantiation)\n", - "* \\_\\_new\\_\\_, \\_\\_init\\_\\_, \\_\\_del\\_\\_\n", - "* 類別屬性\n", - "* 類別方法\n", - "* 靜態方法\n", - "* 物件屬性\n", - "* 物件方法\n", - "* 繼承\n", - "* 多型" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 定義類別\n", - "class Human:\n", - " pass" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 生成物件\n", - "human1 = Human()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 定義物件屬性\n", - "human1.name = \"Victor\"" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "human2 = Human()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "human2.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# __new__(): 要生成物件時被呼叫,初學者通常不會實作這個方法。\n", - "# __init__(): 要初始化物件時被呼叫\n", - "# __del()__: 要刪除物件時被呼叫\n", - "\n", - "class Human:\n", - " # 類別屬性\n", - " count = 0\n", - " \n", - " def __init__(self):\n", - " Human.count += 1\n", - " \n", - " def __del__(self):\n", - " Human.count -= 1\n", - "\n", - "human1 = Human()\n", - "Human.count" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "human2 = Human()\n", - "Human.count" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "del human1\n", - "Human.count" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "del human2\n", - "Human.count" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 增加兩個方法,描述物件的行為\n", - "\n", - "class Human:\n", - " # 類別屬性\n", - " count = 0\n", - " \n", - " def __init__(self, name):\n", - " self.name = name\n", - " Human.count += 1\n", - " \n", - " def __del__(self):\n", - " Human.count -= 1\n", - " \n", - " def sleep(self):\n", - " print(self.name, \"sleeps!\")\n", - " \n", - " def attack(self):\n", - " print(self.name, \"attacks with bare hands.\") \n", - "\n", - "human1 = Human(\"John\")\n", - "human1.sleep()\n", - "human1.attack()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "# 繼承\n", - "class Knight(Human):\n", - " pass\n", - "\n", - "# 父類別的方法被繼承下來了\n", - "knight1 = Knight('Jack')\n", - "knight1.sleep()\n", - "knight1.attack()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "# 多型\n", - "class Knight(Human):\n", - " def attack(self):\n", - " print(self.name, \"attacks with a sword.\")\n", - "\n", - "class Wizard(Human):\n", - " def attack(self):\n", - " print(self.name, \"attacks with a spell.\")\n", - "\n", - "human1 = Knight(\"David\")\n", - "human2 = Wizard(\"Tom\")\n", - "\n", - "group1 = [human1, human2]\n", - "\n", - "for man in group1:\n", - " man.attack()" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "subslide" - } - }, - "outputs": [], - "source": [ - "class Human:\n", - " # 類別屬性\n", - " count = 0\n", - " \n", - " def __init__(self, name):\n", - " self.name = name\n", - " Human.count += 1\n", - " \n", - " def __del__(self):\n", - " Human.count -= 1\n", - " \n", - " def sleep(self):\n", - " print(self.name, \"sleeps!\")\n", - " \n", - " def attack(self):\n", - " print(self.name, \"attacks with bare hands.\")\n", - " \n", - " @staticmethod\n", - " def fight(man1, man2):\n", - " print(man1.name, \"fights\", man2.name)\n", - " \n", - " @classmethod\n", - " def default(clz):\n", - " return clz('John Doe')" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": true, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "human3 = Human.default()\n", - "human3.name" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": { - "collapsed": false, - "slideshow": { - "slide_type": "fragment" - } - }, - "outputs": [], - "source": [ - "Human.fight(human1, human2)" - ] - } - ], - "metadata": { - "anaconda-cloud": {}, - "celltoolbar": "Slideshow", - "kernelspec": { - "display_name": "Python [default]", - "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.2" - }, - "livereveal": { - "scroll": true - }, - "nbpresent": { - "slides": {}, - "themes": { - "default": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", - "theme": { - "56b38c57-4ffe-478a-9f92-8ca64a17c67c": { - "id": "56b38c57-4ffe-478a-9f92-8ca64a17c67c", - "palette": { - "19cc588f-0593-49c9-9f4b-e4d7cc113b1c": { - "id": "19cc588f-0593-49c9-9f4b-e4d7cc113b1c", - "rgb": [ - 252, - 252, - 252 - ] - }, - "31af15d2-7e15-44c5-ab5e-e04b16a89eff": { - "id": "31af15d2-7e15-44c5-ab5e-e04b16a89eff", - "rgb": [ - 68, - 68, - 68 - ] - }, - "50f92c45-a630-455b-aec3-788680ec7410": { - "id": "50f92c45-a630-455b-aec3-788680ec7410", - "rgb": [ - 155, - 177, - 192 - ] - }, - "c5cc3653-2ee1-402a-aba2-7caae1da4f6c": { - "id": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", - "rgb": [ - 43, - 126, - 184 - ] - }, - "efa7f048-9acb-414c-8b04-a26811511a21": { - "id": "efa7f048-9acb-414c-8b04-a26811511a21", - "rgb": [ - 25.118061674008803, - 73.60176211453744, - 107.4819383259912 - ] - } - }, - "rules": { - "blockquote": { - "color": "50f92c45-a630-455b-aec3-788680ec7410" - }, - "code": { - "font-family": "Anonymous Pro" - }, - "h1": { - "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", - "font-family": "Lato", - "font-size": 8 - }, - "h2": { - "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", - "font-family": "Lato", - "font-size": 6 - }, - "h3": { - "color": "50f92c45-a630-455b-aec3-788680ec7410", - "font-family": "Lato", - "font-size": 5.5 - }, - "h4": { - "color": "c5cc3653-2ee1-402a-aba2-7caae1da4f6c", - "font-family": "Lato", - "font-size": 5 - }, - "h5": { - "font-family": "Lato" - }, - "h6": { - "font-family": "Lato" - }, - "h7": { - "font-family": "Lato" - }, - "pre": { - "font-family": "Anonymous Pro", - "font-size": 4 - } - }, - "text-base": { - "font-family": "Merriweather", - "font-size": 4 - } - } - } - } - } - }, - "nbformat": 4, - "nbformat_minor": 0 -}