Python Programming weicc Computer Center CS NCTU Outline

  • Slides: 89
Download presentation
Python Programming weicc

Python Programming weicc

Computer Center, CS, NCTU Outline q Introduction q Overview • Python • Why use

Computer Center, CS, NCTU Outline q Introduction q Overview • Python • Why use Python • Python 3 or Python 2 ? q Python data type • boolean, int, float, str • list, tuple • dictionary, set q Python • for, if, while, try • function, class 2 q Python class • • super() self property __init__ q Generator & Decorator q Python with PEP 8 • What is PEP 8 • How use

Computer Center, CS, NCTU Introduction q 直譯式語言 • Python, Java. Script, Perl, Ruby, PHP

Computer Center, CS, NCTU Introduction q 直譯式語言 • Python, Java. Script, Perl, Ruby, PHP • But not: Go, C, C++, JAVA q 自動記憶體管理 • Python, Java. Script q 具有大量函式庫 • • sys, os, ftplib, smtp requests, ldap 3, Num. Py, Pandas, matplotlib Py. Py, Cpython Django (framework) q 膠水程式 3

Computer Center, CS, NCTU 4

Computer Center, CS, NCTU 4

Computer Center, CS, NCTU 5 Overview q Python • Beautiful, Explicit, Simple • Complex,

Computer Center, CS, NCTU 5 Overview q Python • Beautiful, Explicit, Simple • Complex, Flat, Sparse • Readability q 創作者 Guido van Rossum • 仁慈的獨裁者 q ABC (programming language) 的繼承

Computer Center, CS, NCTU 6 HOW TO RETURN words document: PUT {} IN collection

Computer Center, CS, NCTU 6 HOW TO RETURN words document: PUT {} IN collection FOR line IN document: FOR word IN split line: IF word not. in collection: INSERT word IN collection RETURN collection

Computer Center, CS, NCTU Overview q Python • Beautiful, Explicit, Simple • Complex, Flat,

Computer Center, CS, NCTU Overview q Python • Beautiful, Explicit, Simple • Complex, Flat, Sparse • Readability q 創作者 Guido van Rossum • 仁慈的獨裁者 q ABC (programming language) 的繼承 q 開放語言 • 與 C 語言結合能力非常出色 7

Computer Center, CS, NCTU Python >>> import this The Zen of Python, by Tim

Computer Center, CS, NCTU Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! 8

q 誰在使用 Computer Center, CS, NCTU 9 Why use Python

q 誰在使用 Computer Center, CS, NCTU 9 Why use Python

Computer Center, CS, NCTU Why use Python q 對剛接觸程式語言的人友善 q Python 的使用範圍廣泛 • Web,

Computer Center, CS, NCTU Why use Python q 對剛接觸程式語言的人友善 q Python 的使用範圍廣泛 • Web, GUI application, Chatbot q ML 與 AI 的應用,雲端運用 • Spark • Tensor. Flow q 敏捷 (Agile) 開發 q Python 優雅而高捷 • 優秀的開發速度 • 簡單的交接時間 10

Computer Center, CS, NCTU 11 Python 2 or Python 3 q 目前在 Linux 中還有大量

Computer Center, CS, NCTU 11 Python 2 or Python 3 q 目前在 Linux 中還有大量 Python 2 語言 q 目前在眾多商用 solution 中 Python 2 仍然存在 • Instagram Makes a Smooth Move to Python 3 • https: //thenewstack. io/instagram-makes-smooth-movepython-3/ q Python 2 轉移 Python 3 成本高 q Python 2. 7 將於 2020 年退役 • https: //pythonclock. org/

Computer Center, CS, NCTU Python 2 or Python 3 q print • Python 2

Computer Center, CS, NCTU Python 2 or Python 3 q print • Python 2 : print “I am good guy!” • Python 3 : print(“I am good guy!”) q Utf-8 • Python 2: ASCII str() and unicode() • Python 3: Utf-8 q Range • range and xrange -> range 12

Computer Center, CS, NCTU 13 Python 2 or Python 3

Computer Center, CS, NCTU 13 Python 2 or Python 3

Computer Center, CS, NCTU 14 How to use Python q Text editor • Atom,

Computer Center, CS, NCTU 14 How to use Python q Text editor • Atom, VS code, Sublime • 以上都支援 PEP 8 q IDE • Py. Charm, Anaconda • Jupyter

Computer Center, CS, NCTU PYTHON DATA TYPE 15

Computer Center, CS, NCTU PYTHON DATA TYPE 15

Computer Center, CS, NCTU 16 Python Data type q int • 在 Python 2

Computer Center, CS, NCTU 16 Python Data type q int • 在 Python 2 整數為 32 bit Ø – 2, 147, 483, 648 到 2, 147, 483, 647 Ø 具有 long 型態 • 在 Python 3 下沒有邊界

Computer Center, CS, NCTU 17 Python Data type q float • float(True) Ø 1.

Computer Center, CS, NCTU 17 Python Data type q float • float(True) Ø 1. 0 • float(False) Ø 0. 0

Computer Center, CS, NCTU Python Data type q str • PEP 8 Ø “Iamgoodguy”

Computer Center, CS, NCTU Python Data type q str • PEP 8 Ø “Iamgoodguy” – 多用在給人看的字串 Ø ’Iamgoodguy’ – 多用在給機器的字串 • str + str Ø “Iamgoodguy” + “Iambadguy” • str * int Ø “Iamgoodguy” * 4 18

Computer Center, CS, NCTU 19 Python Data type q list • [‘pen’, ‘pineapple’, ‘apple’]

Computer Center, CS, NCTU 19 Python Data type q list • [‘pen’, ‘pineapple’, ‘apple’] Ø append() Ø extend() Ø insert() Ø remove() Ø pop() Ø index() Ø count() Ø join() Ø sort() Ø len()

Computer Center, CS, NCTU 20 Python Data type q tuple • (‘pen’, ‘pineapple’, ‘apple’)

Computer Center, CS, NCTU 20 Python Data type q tuple • (‘pen’, ‘pineapple’, ‘apple’) Ø 無法任意修改內容 Ø 沒有 append, insert • 內容保存完整 • 佔用空間小

Computer Center, CS, NCTU 21 Python Data type q dict • {‘a’: ‘aaa’, ‘b’:

Computer Center, CS, NCTU 21 Python Data type q dict • {‘a’: ‘aaa’, ‘b’: ‘bbb’, ‘c’: ‘ccc’} Ø keys() Ø values() Ø items() • 一般 json 會從這個形態轉錄

Computer Center, CS, NCTU Python Data type q set • {‘pen’, ‘pineapple’, ‘apple’} •

Computer Center, CS, NCTU Python Data type q set • {‘pen’, ‘pineapple’, ‘apple’} • in Ø ‘pen’ in demo. Set – True Ø ‘kevin’ in demo. Set – False • 基本運算 Ø 交集 & intersection() Ø 聯集 | union() Ø 差集 - difference() Ø 互斥 ^ symmetric_difference() 22

Computer Center, CS, NCTU PYTHON OPERATOR 23

Computer Center, CS, NCTU PYTHON OPERATOR 23

Computer Center, CS, NCTU 25 Python operator q for • break 跳出迴圈 • continue

Computer Center, CS, NCTU 25 Python operator q for • break 跳出迴圈 • continue 跳過

q while Computer Center, CS, NCTU 26 Python operator

q while Computer Center, CS, NCTU 26 Python operator

q try Computer Center, CS, NCTU 27 Python operator

q try Computer Center, CS, NCTU 27 Python operator

Computer Center, CS, NCTU 28 Python operator q try • 沒有 「要就好好做,要不然就不要做」 • try

Computer Center, CS, NCTU 28 Python operator q try • 沒有 「要就好好做,要不然就不要做」 • try 開頭 • except 判別例外 • raise Ø 不在 except 中 > 出現以下例外 Name. Error, Type. Error Concrete exceptions Ø 在 except 中 > 以例外回傳

Computer Center, CS, NCTU 29 Python operator q func • • def demo. Func(arg

Computer Center, CS, NCTU 29 Python operator q func • • def demo. Func(arg 1=‘kevin’, arg 2): *args tuple **kwargs dictionary 內部函示

Computer Center, CS, NCTU 31 Python class

Computer Center, CS, NCTU 31 Python class

q 繼承 Computer Center, CS, NCTU 32 Python class

q 繼承 Computer Center, CS, NCTU 32 Python class

q 複寫 Computer Center, CS, NCTU 33 Python class

q 複寫 Computer Center, CS, NCTU 33 Python class

q 添加 Computer Center, CS, NCTU 34 Python class

q 添加 Computer Center, CS, NCTU 34 Python class

q super Computer Center, CS, NCTU 35 Python class

q super Computer Center, CS, NCTU 35 Python class

Computer Center, CS, NCTU 36 Python class q 特殊使用 • __eq__(): • 官方文件

Computer Center, CS, NCTU 36 Python class q 特殊使用 • __eq__(): • 官方文件

Computer Center, CS, NCTU 37 Python class q 特殊用法 • • • __ne__ !=

Computer Center, CS, NCTU 37 Python class q 特殊用法 • • • __ne__ != __lt__ < __gt__ > __le__ <= __ge__ >=

Computer Center, CS, NCTU 38 Python class q Property • • • Python 無需使用

Computer Center, CS, NCTU 38 Python class q Property • • • Python 無需使用 getter 以及 setter 不過仍可以達成相同功能 @ property @<func>. setter 可以達成唯讀效果

Computer Center, CS, NCTU 39 Python class

Computer Center, CS, NCTU 39 Python class

Computer Center, CS, NCTU 40 Python class

Computer Center, CS, NCTU 40 Python class

Computer Center, CS, NCTU 41 Python class

Computer Center, CS, NCTU 41 Python class

Computer Center, CS, NCTU 42 Generator & Decorator q Python tool for special case

Computer Center, CS, NCTU 42 Generator & Decorator q Python tool for special case q Generator 產生器 • Python 序列建立物件 • range() q Decorator 裝飾器 • 接收一個函式,並回傳另一個函式

Computer Center, CS, NCTU 43 Generator q 用途 • Function 重複呼叫,紀錄上一次動作 • 減少記憶體用量 q

Computer Center, CS, NCTU 43 Generator q 用途 • Function 重複呼叫,紀錄上一次動作 • 減少記憶體用量 q 使用 • 不使用 return • 利用 yield 參考: What does the “yield” keyword do?

Computer Center, CS, NCTU 44 Generator

Computer Center, CS, NCTU 44 Generator

Computer Center, CS, NCTU 45 Decorator q Decorator 可以是 Function 也可以是 Class q Decorator

Computer Center, CS, NCTU 45 Decorator q Decorator 可以是 Function 也可以是 Class q Decorator 可以帶入參數 • 可以參考 • Python Decorator 四種寫法範例 Code q 做 Function 的修飾用途 • 預先處理函式 • 以及後續處理 • 包裝 Python 函式

Computer Center, CS, NCTU 46 Decorator

Computer Center, CS, NCTU 46 Decorator

Computer Center, CS, NCTU 47 Python PEP 8 q Coding style in Python q

Computer Center, CS, NCTU 47 Python PEP 8 q Coding style in Python q PEP 8 is set that contains rules of best coding practices that needs to be followed. If those practices and conventions are not followed, PEP 8 gives errors - Quora q 程式的閱讀次數遠高於撰寫次數 • 因此程式更應該專注於閱讀容易度

Computer Center, CS, NCTU 48 What is PEP 8 is SHIT !!

Computer Center, CS, NCTU 48 What is PEP 8 is SHIT !!

Computer Center, CS, NCTU 50 How use PEP 8 q pip 3 install pycodestyle

Computer Center, CS, NCTU 50 How use PEP 8 q pip 3 install pycodestyle q pycodestyle << python file >>

Computer Center, CS, NCTU 53 Python Library q Standard Library • https: //docs. python.

Computer Center, CS, NCTU 53 Python Library q Standard Library • https: //docs. python. org/3/library/ (英文 3. 6. 4) • https: //docs. python. org. tw/3/library/ (中文 3. 5. 2) q Standard library • os, sys, configparser, logging, getopt, json, unittest q The third part library • requests, numpy

Computer Center, CS, NCTU PYTHON LIBRARY 54

Computer Center, CS, NCTU PYTHON LIBRARY 54

Computer Center, CS, NCTU Python 3 -v q 詳細模式 q demo • • 找

Computer Center, CS, NCTU Python 3 -v q 詳細模式 q demo • • 找 this module python 3 –v import this Find # /Library/Frameworks/Python. framework/Versions/3. 6/lib/python 3. 6/__pycache__/this. cpython 36. pyc matches /Library/Frameworks/Python. framework/Versions/3. 6/lib/python 3. 6/this. py • Cat /Library/Frameworks/Python. framework/Versions/3. 6/lib/python 3. 6/this. py 55

Computer Center, CS, NCTU 56 The Zen of Python

Computer Center, CS, NCTU 56 The Zen of Python

Computer Center, CS, NCTU 57 Outline q os q configparser q logging q getopt

Computer Center, CS, NCTU 57 Outline q os q configparser q logging q getopt q json q requests q numpy q Install python 3 q pipenv

Computer Center, CS, NCTU 59 os q os. rename(src, dst) q 將 src 改名為

Computer Center, CS, NCTU 59 os q os. rename(src, dst) q 將 src 改名為 dst • 官方文件 q os. remove(path) q 刪除檔案 • 官方文件

Computer Center, CS, NCTU os q os. chmod(path, mode) q 變更權限 • mode 八進位(0

Computer Center, CS, NCTU os q os. chmod(path, mode) q 變更權限 • mode 八進位(0 o 400),或是 stat. S_IRUSR • 官方文件 q os. chown(path, uid, gid) q 變更擁有者 • Unix/Linux/Mac 獨有 • uid, gid 使用者ID數字,群組ID數字 • 官方文件 60

Computer Center, CS, NCTU os q os. mkdir(path) • 建立目錄 q os. rmdir(path) •

Computer Center, CS, NCTU os q os. mkdir(path) • 建立目錄 q os. rmdir(path) • 刪除目錄 q os. listdir(path) • 列出所有目錄 q os. chdir(path) • 變更目前目錄 61

Computer Center, CS, NCTU 62 configparser q 解析 INI 檔案 • INI file Informal

Computer Center, CS, NCTU 62 configparser q 解析 INI 檔案 • INI file Informal standard for configuration files Simple text files with sections, properties, and values q 內建函式庫 q 官方文件

Computer Center, CS, NCTU 63 configparser

Computer Center, CS, NCTU 63 configparser

Computer Center, CS, NCTU 64 configparser

Computer Center, CS, NCTU 64 configparser

Computer Center, CS, NCTU 65 logging q 不要使用 print() q Logging Level • •

Computer Center, CS, NCTU 65 logging q 不要使用 print() q Logging Level • • • CRITICAL ERROR WARNING INFO DEBUG NOTSET

Computer Center, CS, NCTU 66 logging

Computer Center, CS, NCTU 66 logging

Computer Center, CS, NCTU 67 getopt q 外部參數 • 可以用 sys 處理 • getopt

Computer Center, CS, NCTU 67 getopt q 外部參數 • 可以用 sys 處理 • getopt 表現更好 q 內建函式庫

Computer Center, CS, NCTU 68 getopt

Computer Center, CS, NCTU 68 getopt

Computer Center, CS, NCTU 69 json { "first. Name": "John", "last. Name": "Smith", "age":

Computer Center, CS, NCTU 69 json { "first. Name": "John", "last. Name": "Smith", "age": 25, "address": { "street. Address": "21 2 nd Street", "city": "New York", "state": "NY", "postal. Code": "10021" }, "phone. Number": [ { "type": "home", "number": "212 555 -1234“ }, { "type": "fax", "number": "646 555 -4567“ } ], "gender": { "type": "male“ } q Java. Script Object Notation • human-readable text q json and simplejson • json was added in 2. 6 }

q json. dumps Computer Center, CS, NCTU 70 json

q json. dumps Computer Center, CS, NCTU 70 json

q json. loads Computer Center, CS, NCTU 71 json

q json. loads Computer Center, CS, NCTU 71 json

Computer Center, CS, NCTU json q json and yaml { "first. Name": "John", "last.

Computer Center, CS, NCTU json q json and yaml { "first. Name": "John", "last. Name": "Smith", "age": 25, "address": { "street. Address": "21 2 nd Street", "city": "New York", "state": "NY", "postal. Code": "10021" }, "phone. Number": [ { "type": "home", "number": "212 555 -1234“ }, { "type": "fax", "number": "646 555 -4567“ } ], "gender": { "type": "male“ } } 72

Computer Center, CS, NCTU json q json and XML { "first. Name": "John", "last.

Computer Center, CS, NCTU json q json and XML { "first. Name": "John", "last. Name": "Smith", "age": 25, "address": { "street. Address": "21 2 nd Street", "city": "New York", "state": "NY", "postal. Code": "10021" }, "phone. Number": [ { "type": "home", "number": "212 555 -1234“ }, { "type": "fax", "number": "646 555 -4567“ } ], "gender": { "type": "male“ } } 73

Computer Center, CS, NCTU 74 requests q http protocol • get, post, put, delete

Computer Center, CS, NCTU 74 requests q http protocol • get, post, put, delete • Document example: Open. Stack Identity API q Google docs API • Document q 官方文件

Computer Center, CS, NCTU 75 requests

Computer Center, CS, NCTU 75 requests

Computer Center, CS, NCTU 76 requests

Computer Center, CS, NCTU 76 requests

Computer Center, CS, NCTU 77 requests q Code sample q Github code • import

Computer Center, CS, NCTU 77 requests q Code sample q Github code • import json • import requests • from lxml import etree

Computer Center, CS, NCTU 78 numpy q mathematical functions library • for large, multi-dimensional

Computer Center, CS, NCTU 78 numpy q mathematical functions library • for large, multi-dimensional arrays and matrices • with a large collection of high-level mathematical functions q ndarray data • n-dimensional array • ndim(維度), shape(形狀), dtype(數值類型)

Computer Center, CS, NCTU 79 numpy

Computer Center, CS, NCTU 79 numpy

Computer Center, CS, NCTU 80 numpy

Computer Center, CS, NCTU 80 numpy

Computer Center, CS, NCTU 81 numpy q numpy and pandas and matplotlib q Pandas

Computer Center, CS, NCTU 81 numpy q numpy and pandas and matplotlib q Pandas

Computer Center, CS, NCTU 82 numpy q Numpy and Pandas and matplotlib q matplotlib

Computer Center, CS, NCTU 82 numpy q Numpy and Pandas and matplotlib q matplotlib

Computer Center, CS, NCTU Install python 3 q On Free. BSD 11. 1 •

Computer Center, CS, NCTU Install python 3 q On Free. BSD 11. 1 • pkg install python 36 • pkg install py 36 -pip • pip-3. 6 install <library> q On Linux (Ubuntu, Cent. OS) • apt install python 3 (default: 3. 5. 2) • pip 3 install <library> • • 83 sudo yum -y install https: //centos 7. iuscommunity. org/ius-release. rpm IUS mean Inline with Upstream Stable sudo yum -y install python 36 u-pip

Computer Center, CS, NCTU pipenv q On Linux, Free. BSD • pip 3 install

Computer Center, CS, NCTU pipenv q On Linux, Free. BSD • pip 3 install pipenv (Linux) • pip-3. 6 install pipenv (Free. BSD) q On Mac. OS • brew install pipenv q Create a new project • • 85 mkdir <demoproject> cd <demoproject> pipenv install <library> pipenv run python 3 <file>. py

q Pipfile Computer Center, CS, NCTU 86 pipenv

q Pipfile Computer Center, CS, NCTU 86 pipenv

q Pipfile Computer Center, CS, NCTU 87 pipenv

q Pipfile Computer Center, CS, NCTU 87 pipenv

Computer Center, CS, NCTU 88 pipenv q pipenv run q pipenv install

Computer Center, CS, NCTU 88 pipenv q pipenv run q pipenv install

Computer Center, CS, NCTU THANK YOU ! 89

Computer Center, CS, NCTU THANK YOU ! 89