# Python :computer: ###### tags: `python` ## 基礎語法 ### 基本操作 一定要有輸入跟輸出 **變數命名規則:** 1. 由英文、數字、底線組成 :abc: 2. 不得以數字開頭 :1234: 3. 不能與Python內建的保留字相同 ==變數指派語法: 變數名稱 = 指派值== **輸入:** 變數=input({提示字串}) | 轉換 |程式 | | -------- | -------- | | 轉整數| 變數=int(input()) | |轉浮點數(小數點)|變數=float(input()) |轉字串|變數=str(input()) **輸出:** print({項目1,項目2}) ==運算式規則:變數 = 運算式== 範例:sum = ((a+b)*3+c*4) / 10 說明:將等號右邊結果存於變數 sum ### 基本運算 **算術運算式** ![](https://i.imgur.com/B3rPZ3Y.png) **關係運算式** ![](https://i.imgur.com/sp8pujt.png) **邏輯運算式** ![](https://i.imgur.com/ujU8vdn.png) ### 判斷結構 ```python= if(條件式1): 程式區塊1 elif(條件式2): 程式區塊2 elif(條件式N): 程式區塊N else: 程式區塊N+1 程式區塊N+2 ``` :::success example:(資料來源:https://zerojudge.tw/ShowProblem?problemid=a003) 1. ![](https://i.imgur.com/UX7lG86.png) 2. ![](https://i.imgur.com/UdWUGlH.png) ::: ### 重複結構 while:不確定迴圈會重複幾次,只要條件式符合,便會重覆迴圈 ```python= while(條件式): 程式區塊 ``` for:已知迴圈會重複幾次,變數會走訪序列中的元素。序列可為==range函式、字串(string)、表列(list)、字典(dict)== ```python= for 變數 in 序列: 程式區塊 ``` ```python= for 變數 in range([起始值,]終止值[,遞增值]): 程式區塊 ``` :::success example: 1. ![](https://i.imgur.com/FbIiV0S.png) 2. ![](https://i.imgur.com/k0fTSO9.png) 3. ![](https://i.imgur.com/ncE2bKc.png) ::: ## Python的格式字串 Python 有 3 種不同的方式來達成字串格式化 (String format), 若輸出較複雜的字串可以使用: * **%-formatting** * **str.format** (Python 2.6+) * **f-string** (Python 3.6+) 透過%將元組中(tuple)的元素依照指定的格式化方式輸出。 * **%s**(字串) * **%d**(十進位整數) * **%f**(浮點數) :::success example: 1. ![](https://i.imgur.com/fiFU9x0.png) 2. ![](https://i.imgur.com/hnHc3tE.png) ::: ## 資料型別:book: ### **字串(string)** :memo: 以單引號('')或雙引號(" ")包含,字串內容視為文字字元 :memo:運算式可用:+(字串連接),[index] (索引值所在字元),[始:終:增] (截取部分字串) :memo: 函數/方法:len(<字串>)(計算字串長度),<字串>.split([sep]) :::success example: 1. ![](https://i.imgur.com/cKB3Hog.png) 2. ![](https://i.imgur.com/tCkDvIX.png) 3. ![](https://i.imgur.com/HrGYcgR.png) 4. ![](https://i.imgur.com/1zoiSqE.png) 5. ![](https://i.imgur.com/sToGxQK.png) ::: ### **列表(list)** * **元組(tuple)** * **字典(dist)** * **集合(set)**