#!/usr/bin/env python # coding: utf-8 # # Python 入門 # # # # ## 事前須知 # # * 今天重點放在幫沒寫過程式的朋友們打基礎 # * 碰到問題請馬上發問 # * 歡迎隨時打斷 (如果有哪邊聽不懂,那一定是我跳太快,請馬上反應) # # # # # ## 等等,Python 到底是啥啊? # # ![Python Icon](images/python-logo-generic.svg) # # # Python 是一個由 Guido van Rossum 在 1991 年 2 月釋出的程式語言, # 發展至今大約過了 20 餘年, # 廣泛使用於科學計算、網頁後端開發、系統工具等地方。 # # Python 這名字是源自於當時 Guido van Rossum 在觀賞的 BBC 喜劇 「Monty Python's Flying Circus」。 # # ![Guido van Rossum](images/Guido_van_Rossum_OSCON_2006.jpg) # # ---- # # > [給稍微有經驗的程式設計師] # > # > Python 主要的特性 # > # > * 強型別 # > * 物件導向 # > * 動態型別 # > * 直譯式 # # # ---- # # 大家可以先連上這個網站, # 可以直接在網頁上面寫 Python 練習 : **https://try.jupyter.org/** # # ---- # ## 基本運算 # In[1]: 1+2 # 加法 # In[2]: 3-4 # 減法 # In[3]: 5*6 # 乘法 # In[4]: 7/8 # 除法 # In[5]: 7//8 # 除法,無條件捨去到個位數 # In[6]: 10%9 # 取餘數 # In[7]: 2 ** 10 # 指數 # In[8]: 2 ** (1/2) # 開根號 # In[9]: 1+2j # 複數 (這裡虛部用 j 表示) # In[10]: (1+2j) * (3+4j) # 複數乘法 # In[11]: 2 ** (1+2j) # 複數指數 # In[12]: abs(-1) # absolute, 絕對值 # In[13]: abs(1+2j) # absolute, 絕對值 # In[14]: round(3.1415926, 3) # 四捨五入到小數點後第 3 位 # In[15]: round(3.1415926, 4) # 四捨五入到小數點後第 4 位 # # 熟能生巧 # # 練習以下狀況 # # * 42 的 100 次方 # * 虛數 i 的平方 # * 42 的四次方根 # # 補充 : 運算有先後順序,可以用括弧來確保自己想要的順序 # # 賦值 (Assign) # # 用 `=` 來給名字 # In[16]: a = 1 b = 1.5 c = "asd" # # 型別 (Type) # # 在程式語言中,型別概念上來說就像是物品的種類,例如:「這群是筆,那群是橡皮擦」。 # # # ## Python 的內建型別 (Built-in Types) # # * int (整數) # * float (浮點數) # * complex (複數) # * str (字串) # * tuple # * list # * dict # * set # * ... # In[17]: type(42) # 用 type 可以得知型別 # In[18]: type(3.14159265358979323846) # In[19]: "測試" # str, 字串 # In[20]: """ 我 是 多 行 字 串 """ # 用 3 個 " 夾起來 # In[21]: ''' 我 是 多 行 字 串 ''' # 也可以用 3 個 ' 夾起來 # In[22]: (42, 'O w O') # tuple, 可以放入各種東西的大箱子,放完後不能更動 # In[23]: foo = (42, 'O w O') foo[0] # subscript operator 可以取出其中的值 # 注意,index 從 0 開始算 # In[24]: [42, 'O w O'] # list 和 tuple 相似,但放完後可以更動 # > 結構 (給比較有經驗的人) # # ![Python Dict](images/python-structure-list.png) # In[25]: {'a': 1, 'b': 42} # dict,冒號左邊的是 key、右邊的是 value,用 key 可以查到 value (想像查字典的狀況) # In[26]: d = {'a': 1, 'b': 42} d['b'] # > 結構 # # ![Python Dict](images/python-structure-dict.png) # In[27]: {1, 2, 3, 3, 3} # set,數學上的集合,裡面的東西不會重複,也沒有順序 # > 結構 # # ![Python Set](images/python-structure-set.png) # In[28]: A = {1, 2, 3} B = {1, 2, 4} A | B # 取聯集 # ![聯集](images/聯集.png) # In[29]: A & B # 取交集 # ![交集](images/交集.png) # In[30]: A ^ B # 取對稱差 # ![對稱差](images/對稱差.png) # In[31]: A - B # 取差集 # ![差集](images/差集.png) # In[32]: dir(int) # 檢查可以使用的 method # In[33]: help(int) # 看文件上的解說 # # 真偽值 # # * True/False # * `>` `>=` `<` `<=` `==` `!=` `in` # * and/or/not # * is # * 各種 empty 狀況 # - 0, 1 # - "", "abc" # - (,), (1, 2) # - [], [1, 2] # - set(), {1, 2} # In[34]: True # In[35]: False # In[36]: 3 > 2 # In[37]: 5 <= 1 # In[38]: 1 != 2 # In[39]: 5 in [1, 2, 3, 4, 5] # In[40]: bool(0) # 用 bool 來看各個資料是 True 還是 False # In[41]: bool(42) # In[42]: bool(""), bool("abc") # In[43]: bool(tuple()), bool((1, 2)) # In[44]: bool([]), bool([1, 2]) # In[45]: bool(set()), bool({1, 2}) # In[46]: bool(dict()), bool({'a': 1, 'b': 42}) # # 流程控制 # # * if ... elif ... else # * for ... in ... # * break # * continue # * while ... else ... # In[47]: if 3 > 2: print('Yes') else: print('Nooooooo, why can you come here?') # 如果 3 > 2 的話印出 'Yes',否則印出 'Nooooooo, why can you come here?' # 注意縮排是有影響的 # In[48]: if 2 > 3: print('No') elif 5 > 4: print('Yes') else: print('@_@?') # 如果 2 > 3 的話印出 'No',要不然 5 > 4 的話就印出 'Yes',否則印出 '@_@?' # In[49]: for i in [1, 2, 3, 4]: # i 會依序變成 1, 2, 3, 4 來執行下面 block 的程式,在這邊則是會被印出來 print(i) # In[50]: for i in [1, 2, 3, 4]: if i == 3: break # 使用 break 來提早離開,當 i 變成 3 時就離開這個 for loop print(i) # In[51]: for i in [1, 2, 3, 4]: print(i) else: print('End') # 如果前面的 for 成功跑完的話會執行這段 # In[52]: for i in [1, 2, 3, 4]: if i == 3: break print(i) else: print('End') # 如果前面的 for 成功跑完的話會執行這段 # In[53]: for i in [1, 2, 3, 4]: if i == 3: continue # continue 可以跳過這次後面的 code,進入下一輪 print(i) else: print('End') # 如果前面的 for 成功跑完的話會執行這段 # In[54]: i = 4 while i > 0: # 當 while 後面接的條件一直符合時就會繼續執行 print(i) i = i - 1 # In[55]: i = 4 while i > 0: # 當 while 後面接的條件一直符合時就會繼續執行 print(i) i = i - 1 else: print('End') # In[56]: i = 4 while i > 0: # 當 while 後面接的條件一直符合時就會繼續執行 if i == 3: break print(i) i = i - 1 else: print('End') # # 更多字串操作 # # * string formatting # * 字串串接 # * slice : `start:stop[:step]` # In[57]: '{} | {}'.format(1, 2) # 用 {} 表示要留著填空,後面用 .format 傳入要填進去的值 # In[58]: '~ {} ~'.format([1, 2, 3, 4]) # In[59]: '上上下下' + '左右左右' + 'BA' # 用 + 可以把字串接起來 # In[60]: s = 'abcdefghijklmnopqrstuvwxyz' # In[61]: s[0] # In[62]: s[1:4] # index 1 到 index 3 (index 4 結束) # In[63]: s[-1] # 負的 index 會倒回去 # In[64]: s[1:8:2] # index 1 到 index 7,每次跳兩步 # In[65]: s[-1:-9:-2] # In[66]: s[::-1] # 不指定的話會自動帶入值 # # Function # # 一些常用的 code 會寫成 function,之後要使用時直接呼叫就可以了 # In[67]: def hello(): # 用 def 定義一個 function 叫作 hello,負責輸出 'Hello ~' print('Hello ~') hello() # 呼叫 # In[68]: def f_42(): return 42 # 用 return 來回傳資料 x = f_42() print(x) # In[69]: def f(a, b=3): # a 和 b 是參數,b 預設是 3 return a+b x = f(10) y = f(10, 5) print(x, y) # # 總複習 # # * 認識 Python # * 基本運算 # - 加減乘除 # - 取餘數 # - 指數 # - 複數 # - 除法,無條件捨去到個位數 (//) # - 絕對值 (abs) # - 四捨五入 (round) # * 型別 # - 基本型別 # + int # + float # + str # * `"` # * `'` # * `"""` # * `'''` # * `\` escape # + tuple # + list # + dict # + set # * `|` # * `&` # * `^` # * 輔助工具 # - dir # - help # - type # * 賦值 (Assign) # * 真偽值 # - True/False # - `>` `>=` `<` `<=` `==` `!=` `in` # - and/or/not # - is # - 各種 empty 狀況 # + 0, 1 # + "", "abc" # + (,), (1, 2) # + [], [1, 2] # + set(), {1, 2} # * 流程控制 (注意冒號和縮排) # - if ... elif ... else # - for ... in ... # - break # - continue # - while ... else ... # * 更多字串操作 # - format string # - 字串串接 # - slice : `start:stop[:step]` # * function # - def # - return # - arguments # + defaults # - function call # * Slice # - slice(start, stop[, step]) # - a[0], a[-1], a[1:99:3], a[-1:-11:-2], a[::-1] (不打的話就自動帶入頭尾), range(-1, -11, -2) # # # 其他還有很多還沒包含的議題 (未全部列出) # # # ## Python 內建 features # # * method # - list.pop, list.remove, list.append # - ... # * 轉型別 # - str(123) # * 打包 # - `*` # - `**` # * module # - import ... # - from ... import ... # * class # - method # * list comprehension # * lambda function # * 內建函數 (builtins) # - len # - sum # - count # * 三元運算子 # * 生成器 (generator / yield) # * 例外事件處理 (try-except) # * 函數裝飾 (decorator) # * metaprogramming # * 更多字串操作 # - string encoding/decoding # * Python 3 和 Python 2 的差異 # # ## Python - 科學運算 # # ### SciPy # # * NumPy - 矩陣相關操作 # * Matplotlib - plotting # * SymPy - symbolic mathematics # * Pandas - Python Data Analysis Library # * Scikits # # # ## 網頁開發 # # * Django # * Flask # # 其他資源 # # * [PyFormat Using % and .format() for great good!](https://pyformat.info/) # * [CheckiO](https://checkio.org/) # * [Python Documentation](https://docs.python.org/3/) # * [The Hitchhiker's Guide to Python!](http://docs.python-guide.org/en/latest/) # * [Dive Into Python 3](http://getpython3.com/diveintopython3/) # * [Why Are There So Many Pythons? A Python Implementation Comparison](http://www.toptal.com/python/why-are-there-so-many-pythons) # # CheckiO # # [CheckiO](https://checkio.org/) 是一個專門為 Python 做的線上解題系統,上面有許多題目可以練習,解出來後還可以看別人的解法來學習、討論。 # # ![CheckiO](images/checkio-01.png)![CheckiO](images/checkio-02.png)![CheckiO](images/checkio-03.png)![CheckiO](images/checkio-04.png)![CheckiO](images/checkio-05.png) # # 安裝 # # ## Linux # # 通常系統內建就會有 Python,另外可以用內建的套件管理裝 Python 3 # # # ## Mac # # 系統上有 Python 2.7,可以用 MacPorts 或 Homebrew 安裝 Python 3 # # # ## Windows # # 可以從官網下載安裝檔 # # ![Python on Windows](images/python-windows.png) # # 額外資訊 # # ## Python 實作 # # [名詞解釋] # # * "Python" 指的是程式語言的規範 # * "CPython" 是官方 "Python" 直譯器實作的名稱 # # ### CPython # # Python 官方實作,核心部份使用 C 語言撰寫,部份 Standard Library 使用 Python 撰寫,對於 Python 的支援最完整。 # # # ### PyPy # # 利用 JIT (just-in-time compiler) 技術加速 Python 程式的專案,目標是要相容於 CPython 的同時大幅提升效能。 # # > [更多訊息] # > # > PyPy 是用 RPython framework 撰寫的 Python interpreter,RPython 是一個 Python 的子集,RPython 限制了一些比較動態的 feature, # > 藉此可以做 type inference,之後再做分析、優化,並生出 Tracing JIT、Garbage Collector。 # # # ### Jython # # Java 版的 Python 實作,可以把 Python code 轉成 Java bytecode 在 JVM (Java Virtual Machine) 執行,除此之外可以 import Java 的 class # # # ### IronPython # # 利用 .NET framework 實作的 Python,可以使用 .NET framework 的 libraries