[TOC] # 基礎程式設計 Python ## 基本觀念 ### Creating Variables 創建變數 * `=` **賦值運算子** 用來給變數一值並決定其形態 ```python= a = 17 #int b = "champion" #string c = True #bool ``` ### print()的sep分隔和end結束 * `sep=` 可以改變兩個變數間的分隔(預設為`space`空白鍵) ```python= a,b = 5,10 print(a,b) print(a,b,sep=',') # 5 10 # 5,10 ``` * `end=` 可以改變輸出完到下一輸出的格式(預設為`\n`,即換行) Ex : * `\\` -> print `\` * `\'` -> print `'` * `\"` -> print `"` ```python= a,b,c = 10,20,30 print(a) print(b,end='\t') # tab print(c) # 10 # 20 30 ``` ### Comment Statements 註解敘述 * `# ...` -> 單行 * `''' ... '''` -> 多行 ```python= # one line ''' can comment multiple lines ''' ``` ## Output Formatting 格式化輸出 ### %運算器 在要輸入的字串裡打要輸出的**字元數量**、**精確度**及**型態**,在`%()`放入對應的值 Ex:`%6.3f`表示顯示六格字元,精確度到小數點第3位,型態為 `float` ```python= print("pi is :%.2f " %(3.14159)) # pi is : 3.14 ``` * `%s` -> 字串 * `%d` -> 整數 * `%f` -> 浮點數 ```python= name , score = "hmh",31 print("%s 's score is %d." %(name,score)) # hmh 's score is 31. ``` ### format{} `{}`表示要**替換的參數**,`.format()`放入**對應的參數** ```python= print('0110 + {} = {}.'.format(1011,10001)) # 0110 + 1011 = 10001. ``` 可以用`{n}`指定要帶入**第n個參數**(由**0**算起) ```python= print('{1} - 0011 = {0}.'.format(1000,1011)) # 1011 - 0011 = 1000. ``` 也可以在`{}`裡給一**參數**,並在`.format()`裡**指定參數** ```python= print('{name1} loves{name2}.'.format(name1='wbr',name2='sm')) # wbr loves sm. ``` ### f-字串 用`f''`包住,在`{}`裡給一參數,且可以`{}`內**運算**及**改變輸出格式** * `+` -> 顯示正號 * `>`、`<` -> 表示靠右、靠左 ```python= a,b = 10,20 print(f'{a} + {b} = {a+b:+7.1f}') # 10 + 20 = +30.0 ``` ## Data Type 資料型態 數值: `int`整數、`float`浮點數、`complex`複數、`bool`布林值 字串: `str`字串 容器: `tuple`、`list`串列、`set`集合、`dict`字典 ### Check Type 查詢型態 * `type( )` ```python= print(type(100)) # <class 'int'> print(type([100])) # <class 'list'> print(type('string')) # <class 'str'> ``` ### Change Type 改變型態 * `int()` -> 轉成`int` * `flaot()` -> 轉成`float` * `bool()` -> 轉成`bool` ## String 字串 字串可以比大小 -> **ASCII code** ```python= print('python' < 'Python') # False print('Python' == 'Python') # True print('y' in 'Python') # True ``` ### String Operators 字串運算子 | 運算子 | 說明 | |:------:|:----------| | ``+`` | 連接 - 在運算符兩側新增值 | | ``*`` | 重複 - 建立新字串,連接相同字串的多個副本 | | ``[]`` | Slice 切片 - 給出給定索引中的字符 | | ``[:]`` | Range Slice 範圍切片 - 給出給定範圍內的字符 | ### Range Slice 範圍切片 基礎: **`[a:b]`**:從第a個字元開始,到第b個字元結束 進階: **`[:b]`**:從頭開始,到第b個字元結束 **`[a:]`**:從第a個字元開始,到尾結束 **`[:]`**:從頭到尾結束 ```python= line = 'HelloWorld' print(line + ' by python') # HelloWorld by python print(line*3) # HelloWorldHelloWorldHelloWorld print(line[5]) # W print(line[-3]) # r print(line[0:7]) # HelloWo print(line[1:-1]) # elloWorl print(line[:6]) # HelloW print(line[4:]) # oWorld print(line[:]) # HelloWorld ``` ## Boolean 布林值 `True` 或 `False` ### Logical Operators 邏輯運算子 | 運算子 | | :---: | | `not` | | `and` | | `or` | ```python= A,B = True,False print(B) # False print(not B) # True print(A and B) # False print(A or B) # True ``` 也可以用`int` ```python= x,y = 0,999 print(x or y) # 999 print(x and y) # 0 print(not x) # True print(not y) # False ``` ## Integer 整數 * `divmod()`-> 計算**商數**和**餘數** ```python= print(divmod(17,5)) # (3,2) ``` ### 進位 初始為**decimal十進位** | 進位制 | 函式 | 表示方式 | | :--------: | :--------: | :--------: | | Binary 二進位 | `bin()` | 0b... | | Octal 八進位 | `oct()` | 0o... | | Hexdecimal 十六進位 | `hex()` | 0x... | ```python= num = 100 print(bin(num)) # 0b1100100 print(oct(num)) # 0o144 print(hex(num)) # 0x64 ``` ### Arithmetic Operators 算術運算子 | 運算子 | 說明 | Example | Result | |:------:|:----------:|:---------:|:-------:| | ``+`` | 加法 | a = 1+2 | a = 3 | | ``-`` | 減法 | a = 20-12 | a = 8 | | ``*`` | 乘法 | a = 2*3 | a = 6 | | ``/`` | 除法 -> <font color="red">float</font> | a = 9/2 | a = 4.5 | | ``%`` | 除法取整數 | a = 9//2 | a = 4 | | ``**`` | 餘數 -> <font color="red">int</font> | a = 9%2 | a = 1 | | ``//`` | 次方 | a = 2**3 | a = 8 | ### 遞增運算子 將**算術運算子**和**賦值運算子**組合 | 運算子 | Example | Same as | |:------:|:---------:|:-------:| | ``+=`` | a += 1 | a = a + 1 | | ``-=`` | a -= 1 | a = a - 1 | | ``*=`` | a /= 2 | a = a * 2 | | ``/=`` | a /= 2 | a = a / 2 | | ``%=`` | a %= 3 | a = a % 3 | | ``**=`` | a **= 2 | a = a ** 2 | | ``//=`` | a //= 3 | a = a // 3 | ### Relational Operator 關係運算子 | 運算子 | 說明 | Example | |:------:|:---------:|:-------:| | ``>`` | 大於 | a > b | | ``<`` | 小於 | a < b | | ``>=`` | 大於等於 | a >= b | | ``<=`` | 小於等於 | a <= b | | ``==`` | 等於 | a == b | | ``!=`` | 不等於 | a != b | ```python= a = 5 b = 3 print(a < b) # False print(b <= a) # True print(a != b) # True print(a == b) # False ``` ### 運算子優先順序 1. `()` 2. `**` 3. `not` , `-( )` 4. `*` , ``/`` , ``%`` , ``//`` 5. ``+`` , ``-`` 6. ``>`` , ``>=`` , ``<`` , ``<=`` 7. ``==`` , ``!=`` 8. `and` , `or` 9. ``=`` ## If Statements If判斷式 If判斷式是程式中的一種條件控制結構,用於根據條件的真假來執行不同的程式塊。 ```python if (Logical condition1): Statement1 elif (Logical condition2): Statement2 else: Statement3 Statement4 ``` ## Loop 迴圈 ### For Loops For迴圈 For 迴圈是 Python 中的一個迴圈控制結構,用於對佇列(例如`list`串列、`str`字串等)中的每個元素進行迭代操作。 * `in` 為**成員運算子** 常和`for`陳述句搭配,用來界定重複的範圍。 ```python for (Variable) in (Sequence): # 執行迴圈內的程式碼 ``` ```python= for i in range(1,6): print(i,end=" ") # 1 2 3 4 5 ``` ```python= fruits = ["apple", "banana", "orange", "grape"] # list串列 for fruit in fruits: print(fruit,end=" ") # apple banana orange grape ``` ### While Loops While迴圈 While 迴圈是 Python 中的另一種迴圈控制結構,它用於當特定條件為真時,重複執行一段程式碼。 ```python while (Condition): # 執行迴圈內的程式碼 ``` ### Continue繼續 和 Break結束 `continue`和`break`是用於迴圈控制的重要關鍵字。`continue`用來跳過這次迴圈,而`break`用來終止迴圈的執行。 :::warning 後面的內容如果沒有更新到HackMD上,請到下面的網址繼續學習 :blue_book:。 https://colab.research.google.com/drive/1DdCV5ZnXk8LmUTX6txpbxScmDiTj85ka?usp=sharing :::