Lecture 1: Basics
python https://www.python.org/ 廣為使用及開源的免費軟體之一 跨平台使用 :Linux, Windows, Mac 可使用別人提供的 library 亦可開放自己整合的 library 貢獻給開源社群 你可以在 study 主機上使用 python, 或在你的筆電上安裝 使用整合好的 Anaconda
連到 study 執行 python 互動式指令列 : 在 >>> 後輸入 python 指令, 按下 enter 後馬上執行 ( 結束時, 按下 ctrl + d).py 檔 ( 類似 GrADS 的.gs 概念 ) 先用 nano 編輯檔案, 串接數個 python 指令 (e.g. test.py) 在 unix 下輸入 python filename (e.g. python test.py)
在你的筆電上 :Let s use Anaconda! 1. 已安裝好許多常用的科學 數學 工程 數據分析的 library 2. 完全開源 (open) 和免費 (free) 3. 支持不同版本的 Python (2.7 3.6), 可自由切換 (-> 安裝不同版本即可使用 ) 4. 提供 spyder 視窗介面
下載 Anaconda download link: https://www.continuum.io/downloads 安裝教學 Windows: https://docs.continuum.io/anaconda/install/windows Mac: https://docs.continuum.io/anaconda/install/mac-os Linux: https://docs.continuum.io/anaconda/install/linux 選擇自己電腦相對應的系統 (Windows/Mac) 選擇 python3.x 的 64-bit version
安裝 Anaconda 1. 雙擊下載好的程式 2. 可以直接套用預設值 ( 一直 next) 3. 結束前, 取消兩個選項 4. 執行 spyder ( 在工作開始列搜尋 spyder ) 5. 出現如下畫面 a. 右邊防火牆 允許存取 b. 左邊取消 check for updates 按 OK
spyder 編輯器 左半邊編輯.py 檔 會有提示可用的 function 按下 tab 鍵也會出現提示可用的 function 執行程式 按工具列的綠色箭頭執行程式 右下角出現執行結果 右上角列出已存在的變數清單 指令查詢等 編輯.py 檔 執行結果
The Basics of Python: Variables Arithmetic Operations IF For Loop Import module
Python: Basic syntax # 符號後是註解 (comment), 可以在一列的開頭或中間加入 reserved word or built-in function ( 變數取名請避開!) and, exec, not, as, finally, or, assert, for, pass, except break, from, print, class, global, raise, continue, if, return def, import, try, del, in, while, elif, is, with, else, lambda, yield 縮排視為不同的 block ( 在 IF 判斷式或迴圈的段落中使用 ) 縮排可以用 tab 或是數個空格 ( 至少一個空格 ) 空格的數量不同, 視為不同的 block (bug 很容易因為這一點而發生 ) python 的每個變數視為一個 object ( 稍後說明 )
Python variables 不需要事先宣告變數, 直接用 = assign value( 賦值 ) 即可 x=3.14 實數變數 變數類型 (data type) 根據被賦予的值決定 ( 之後如果被 assign 不同類型的數值, 該變數的類型就會直接改變 ) x= text 字串變數 確認變數的 data type: type(x) 變數名稱中的大小寫要完全一致 (a A 會當作不同的變數 ) python 可以在同一個指令中對多個變數賦值 x, y = 2, 1 x = 2, y = 1 若想要移除變數, 使用 del x y 常見的 data type: number, string, list, tuple, boolean
Python variable types Number 數值 int : a = 11 float: a = 1.1e-18 complex: a = 4. + 7j String 字串 ( 用 或 夾起 ) e.g. x = Hello World! or x = Hello World! 取出字串的局部 :x [0:3] 注意 :index 從 0 開始計算! [a:b] -- begin at index a and end before index b (e.g., x[0:3] -> Hel ) 不可以對字串的局部做更改,e.g. x[0:3] = Yo! ( 這個是錯誤的語法 ) Boolean 邏輯 只有 True, False 兩種值, 根據邏輯判斷 (IF condition) 的結果決定 兩個 boolean 變數做運算, 會以 True=1, False=0 做整數運算
Python variables: list and tuple list, tuple 類似陣列的概念, 但可以混雜儲存不同型態的資料, 如下所示 List: x = [ 'abcd', 786, 2.23, 'john', 70.2] Tuple: y = ( 'abcd', 786, 2.23, 'john', 70.2) assignment: list 使用 [], tuple 使用 (), 每個元素都用, 分開 list 的大小及元素可以改變 tuple 則不行 ( 類似常數陣列 ) sub-list 或是 sub-tuple 語法類似取出字串局部 : x[0:2] ['abcd', 786 ] y[2:4] (786, 2.23 ) 之後會對 list 有更多介紹
Convert data type 有時候需要不同型態的資料轉換, 例如將字串 10 轉成整數 10 下列為常用的 built-in function int (x) float (x) str (x)
Arithmetic Operators 加法 + string 相加 : 形成新的字串 x = Hello, y = World c = x + y c = HelloWorld 減法 - 乘法 * string 乘一個數字 (int): 字串重複幾次 x = Yo! y = x * 3 y = Yo!Yo!Yo! 除法 / 注意 : 兩個整數相除, 結果是實數 x = 21, y = 10 c = x / y c = 2.1 次方 ** 取餘數 % 整除至最近整數 // 相除後取最接近的整數 ( 整實數 ), 結果的類型取決於兩個變數的類型 : 9//2 = 4 9.0//2.0 = 4.0 11.0//3 = 4.0
Arithmetic Operators 如果要進行下面的運算 a= a+b ( 用 a+b 的結果為 a 重新賦值 ) 在 python 可以改寫成 : a += b 所以算術運算符號可以有 += -= *= /= %= **= //=
Python built-in function sqrt(x) abs(x) max(x1, x2,...) min(x1, x2,...) ceil(x): 無條件進位 floor(x): 無條件捨去 round(x,n): 四捨五入到小數點下第 n 位 (n 可省略, 則使用 default n = 0) 下面函數必須先引入 math 工具才能使用, 在.py 檔先寫入 import math math.exp(x) math.log(x) math.log10(x) math.cos(x), math.sin(x), math.tan(x), math.acos(x), math.asin(x), math.atan(x) math.degrees(x):converts angle x from radians to degrees. math.radians(x):converts angle x from degrees to radians.
Block IF and while if condition1 : statement(s) elif condition2 : statement(s) else: statement(s) while condition : statement(s) (repeatedly executes the statement(s) as long as the given condition is true) 邏輯判斷符號 == (equal)!= (not equal) > (greater than) >= (greater than or equal to) < (less than) <= (less than or equal) is, is not is : 條件比 == 更為嚴格, 必須連 data type 都相同 右圖為範例 (a = 4, data type : int) 邏輯運算 and 交集 or 聯集 not 非
IF and while: syntax 不同數量的空格 ( 或 tab) 縮排, 會被視為不同的 if block 邏輯判斷式可以不用加括號 (), 但是如果有多個或很複雜, 建議加上括號以利閱讀 不管 if, elif, else, for, while, 都需要加上 : Statement 如果很簡短, 可以直接在 : 後面寫出, 例如 if a % 2 == 0: print ( a is even number ) (while for loop 也適用 )
Example of if condition
For loop 迴圈 for x in [list] : statement(s) (iterates over the items in a sequence, such as elements in a list or in a string) e.g., for x in [1,2,3] : y=x+2 print(y) 也可寫成 for x in range(1,4) : y=x+2 print(y) range( ) 經常用來控制迴圈的次數, 但注意 default 是從 0 開始 range(n) 從 0 開始到 n-1 的整數 e.g., range(3) 0,1,2 range(nmin, nmax, interval) 從 nmin 開始, 以間隔 interval 遞增到 nmax-1 的整數 e.g., range(1,8,2) 1, 3, 5, 7
Example for loop for char in message: 逐一取出 message 字串變數裡的元素 ( 字元 )
Simple input/output input( ) 在螢幕上顯示字串, 並等待使用者輸入字串 x = input ( input your name: ) 螢幕上會顯示訊息 input your name:, 使用者輸入的內容, 會用字串類型存到 x 變數 就算使用者輸入數字, 仍然是以字串類型儲存 ( 之後會介紹如何切割字串 (split), 轉為數值 ) print (...) 顯示在螢幕上 e.g. print ( Hello World!! ) 若要一次輸出多個變數至螢幕上, 直接以逗號分開 e.g. print(x,y,z) 也可以 format output( 之後介紹 )
Python is an object-oriented programming language 生活中的例子 : 每個人都有自己的特徵以及可以從事的行動 物件 (object): 不同型態的人 特徵 (attribute): 人名 身高 膚色... 工作 (method): 寫作業 批改作業 出作業... 不同型態的 object 有特定的 attribute and method( 例如 : 學生 可 寫作業 但不能 批改作業 ) 推演到 python 不同的 data type 視為不同的物件 (object), 譬如 int, string 變數儲存的 數值 ( 或字串 ) 則為其 attribute 不同的 object 有各自的 methods( 會使用到這個物件的 attribute 的函式 ), 使用 dir(x) 可以列出清單 要使用物件 x 的 B method, 語法是 : x.b(...) 用 help(x.b) 可以查詢指令用法 method 是特殊指令, 一般不會用到
Modules or package ( 也稱為 library) modules or packages : 通常是其他人寫好的函數或指令, 打包成一個 工具庫 方便分享使用 ( 非 python 內建, 可能會需要下載安裝 ) 本課程會用到的 library: numpy (array), matplotlib ( 基本繪圖 ), basemap ( 地圖 ), netcdf ( 讀 nc 檔 ) 使用方式 :import module_name 在執行工具庫內的指令之前, 就要先把 modules 引進來 ( 不然 python 不會認得非內建的指令 ) 使用工具庫內的指令 :module_name.function (or module_name.constant) 可以使用 import module_name as xxx (xxx 是你自己取的縮寫 ) 使用指令的語法就簡化成 xxx.function, 例如 import math as m x=m.cos(m.pi)
Online resource 官方教學文 1. https://docs.python.org/3.6/tutorial/index.html 2. https://www.tutorialspoint.com/python3/index.htm 3. https://docs.python.org/3.6/ 其他網路資源 / 線上課程 1. http://tech-marsw.logdown.com/blog/2014/09/03/getting-started-with-pythonin-ten-minute 2. http://blog.techbridge.cc/2016/12/17/python101-tutorial/ 3. coursera: https://www.coursera.org/learn/python