# Python基礎 ###### tags: `python` `winter_camp` [TOC] ## Linux下的python * 在終端機直接打`python`即可進入python2的互動模式,`python3`為python3的互動模式 * 若在```python3```後面接檔名,會開始逐行執行該檔案 * 直接執行,在程式第一行加上```#!/usr/bin/env python3```,並用```chmod```將檔案改成可執行檔。 --- ## python基本變數型態 * int * flaot * str ```python= a = 1 b = 1. c = 0.1 d = '1' e = '1' * 10 ``` ```python= a = 1 print(type(a)) b = float(a) print(type(b)) c = str(a) print(type(c)) d = int(c) print(type(d)) ``` --- ## python 運算子 * 與C語言比較 |運算子| C | python | | -------- | -------- | -------- | | 加 | + | + | | 減 | - | - | | 乘 | * | * | | 除 | / | / (//) | | 取餘數 | % | % | | 乘冪 | pow() | ** | | 單行註解 | // | # | * python2 : ```<int>/<int>```為整數除法,與C的結果相同 * python3 : ```<int>/<int>``` : 若無法整除,會自動轉乘float。若不想自動轉型,要用```<int>//<int>``` --- ## 資料型別 ### List list 是一種 python特有的資料格式 用"type()"來查詢的話 會顯示:list python中沒有陣列,只有list,不過list比C的array更強大,它可以自由改變長度,也可以容許在同一個list裡放不同型態的變數 #### list常見的function * ```a=[]``` : 建立的list * ```a=[1, 2, 3]``` : list初始化 * ```a[索引值]``` : list a成員讀取,索引值從0開始 * ```len(a)``` : 回傳list a的長度 * ```a.append(b)``` : 在a尾端加入成員b * ```a.extend(B)``` : 在a尾端接收另一個list B ### Tuple list 是一種 python特有的資料格式 用"type()"來查詢的話 會顯示:tuple tuple跟list很像,唯一的差別是tuple內的資料無法更改。 #### list常見的function * ```a=()``` : 建立的tuple * ```a=(1, 2, 3)``` : tuple初始化 * ```a = (1,)``` : 只有單一成員tuple,初始化記得加```,``` * ```a[索引值]``` : tuple a成員讀取,索引值從0開始 ---- ## 判斷句 * `>`:大於 * `<`:小於 * `>=`:大於或等於 * `<=`:小於或等於 * `==`:等於(vs=:指派) * `!=`:不等於 * `and`:且 * `or`:或 * `not`:非(真假對調) * 這些在python裡也是可以用的 ```python= x=10 y=20 print(x is y) print(x is not y) print(x <= 5 and y <= 5) print(x <= 5 or y <= 5) print("C" in "Python") print("C" in "C++") ``` * 範例 ```python= mood = "happy" if mood is "happy": print("^_^") elif mood is "normal": print("-_-") elif mood is "sad": print("Q_Q") ``` --- ## 迴圈 ### for迴圈 :::info for <迭代變數> in <可迭代變數>: <縮排><其他程式> ::: ## range * 產生一個整數的等差數列存 * 語法:range(start, stop, step) * start:起始值(可省略,預設值為0) * stop:中止值 * step:增值(可省略,預設值為1) * 注意range範圍是**≧start, <stop** * 檢視發法,轉成list * Ex:t=range(0, 6, 2) ```a=list(t) #a=[0, 2, 4]``` --- * C ```C= for(int i=0;i<10;i++){ printf("%d\n", i); } ``` * python ```python= for i in range(10): print(i) ``` ```python= data=[] for i in range(10): data.append(i**2) print(data) ``` * 列出1~a,是2或3的倍數但不是6的倍數的所有整數。 ```python= a=10 for i in range(1, a+1): if i%2 == 0 or i%3 == 0: if i%6 == 0: pass else: print(i) ``` #### 進階應用 https://www.runoob.com/python/python-func-enumerate.html https://www.runoob.com/python/python-func-zip.html ```python= for i,j in enumerate(range(10)): print(i,j) ``` ```python= for i,j in enumerate(zip(range(10),range(1,11))): print(j) ``` ### while迴圈 :::info while <判斷句>: <縮排><其他程式> ::: * C ```c= int cnt = 10; while(cnt--){ printf("%d\n", cnt); } ``` * python ```python= a = 10 while a > 0: print(a) a-=1 ``` ### 自定義函式 :::info def <函數名稱>(<變數1>, <變數2>…): <縮排><函數內容> ::: * 範例 ```python= def ten(): return 10 a = ten() print(a) ``` ```python= def f(x): ans = 5*x**2-3*x-11 s = 5*x-3*x-11 return ans, s a = f(9) print(a) a, b = f(9) print(a) print(b) ``` # HW ## 把下面的C code改成python code (UVA-12503: Robot Instructions) https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=3947 ```C++= #include<stdio.h> int main(){ int init = 1; int time = 3; char command[3] = {'L', 'R', 'S'}; int sc[3] = {0, 0, 2 }; //same as command for (int l=0;l<init;l++){ int ans = 0; int data[time]; for (int i=0;i<time;i++){ char s = command[i]; switch(s){ case 'R': data[i] = 1; break; case 'L': data[i] = -1; break; default: int t = sc[i]; data[i] = data[t-1]; } ans+=data[i]; } printf("%d\n", ans); } } ``` #### ans ```python= time = 3 ans = 0 data = [] command = ['L', 'R', 'S'] sc = [0, 0, 2 ] for j,i in enumerate(command): if i == 'L': ans -= 1 data.append(-1) elif i == 'R': ans += 1 data.append(1) elif i == 'S': l = data[sc[j]-1] ans += l data.append(l) print(ans) ``` ![](https://i.imgur.com/3HDCs8A.png)