# 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 ### 基本運算 **算術運算式**  **關係運算式**  **邏輯運算式**  ### 判斷結構 ```python= if(條件式1): 程式區塊1 elif(條件式2): 程式區塊2 elif(條件式N): 程式區塊N else: 程式區塊N+1 程式區塊N+2 ``` :::success example:(資料來源:https://zerojudge.tw/ShowProblem?problemid=a003) 1.  2.  ::: ### 重複結構 while:不確定迴圈會重複幾次,只要條件式符合,便會重覆迴圈 ```python= while(條件式): 程式區塊 ``` for:已知迴圈會重複幾次,變數會走訪序列中的元素。序列可為==range函式、字串(string)、表列(list)、字典(dict)== ```python= for 變數 in 序列: 程式區塊 ``` ```python= for 變數 in range([起始值,]終止值[,遞增值]): 程式區塊 ``` :::success example: 1.  2.  3.  ::: ## Python的格式字串 Python 有 3 種不同的方式來達成字串格式化 (String format), 若輸出較複雜的字串可以使用: * **%-formatting** * **str.format** (Python 2.6+) * **f-string** (Python 3.6+) 透過%將元組中(tuple)的元素依照指定的格式化方式輸出。 * **%s**(字串) * **%d**(十進位整數) * **%f**(浮點數) :::success example: 1.  2.  ::: ## 資料型別:book: ### **字串(string)** :memo: 以單引號('')或雙引號(" ")包含,字串內容視為文字字元 :memo:運算式可用:+(字串連接),[index] (索引值所在字元),[始:終:增] (截取部分字串) :memo: 函數/方法:len(<字串>)(計算字串長度),<字串>.split([sep]) :::success example: 1.  2.  3.  4.  5.  ::: ### **列表(list)** * **元組(tuple)** * **字典(dist)** * **集合(set)**
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up