# **Python 基礎語法** ### ┏ (゜ω゜)=👉點名表單 discord: ![](https://hackmd.io/_uploads/SkD7YmTlp.png) --- ### 之後的課程規劃 ##### 確定: 10/6 環境架設+基本語法 10/27 dc bot(1) ---Building a bot 11/17 dc bot(2) ---Cogs and making bot alive ##### 暫定: 12/15 AI(1) ---Data classification 12/29 AI(2) ---Pattern recognition --- ## 開始之前 : 安裝Python 直接示範 安裝3.10.11版的是因為之後dc機器人會需要 如果你需要可以參考這篇 : https://hackmd.io/@onion0905/HkZOLFFZj ## 開始之前:IDE > IDE(Integrated Development Environment) : 你寫程式的地方 ### 1.Visual Studio Code ![](https://hackmd.io/_uploads/Sk_t8HgSn.jpg) :::info 方便好用,介面舒服美觀 ::: :::spoiler 安裝 請參考 : https://hackmd.io/@smallshawn95/vscode_write_py ::: ### 2.Pycharm ![](https://hackmd.io/_uploads/rkOC3Jola.png =200x200) :::info 方便好用,介面舒服美觀 有professional版和community版,但前者要錢(不過可以用學生帳號免費申請) 基本上community就夠了 ::: :::spoiler 安裝 請參考 : https://hackmd.io/@ntust-ossda/HktEgqkwi?utm_source=preview-mode&utm_medium=rec ::: ### 3.Embarcadero Dev-C++(如果你只要學Python可以忽略它) ![](https://hackmd.io/_uploads/rJe4HSgB2.jpg) :::info 這是我個人常用的C++ide,很好用 ::: :::spoiler 安裝 1.到 https://www.embarcadero.com/free-tools/dev-cpp ,按下download 2.填一些個人資料後獲取檔案 3.安裝,記得安裝過程中都選擇英文介面,選中文的話會有bug(本人親測) ::: --- # 一、正篇開始 : review ## 變數型態 > 還記得八? | 變數型態 | 中文名稱 | 範例 | |:---------:| ------------ |:----:| | int | 整數 | i=1 | | float | 浮點數 | f=1.5 | | char | 字元 | c='A' | | long long | 長整數 | L=1 | | double | 倍精度浮點數 | d=1.5 | | str | 字串 | s="Hello World!" | :::success 一個好的變數名稱可以這麼宣告 : * 讓人一目了然這個變數的意義 * 建議用英文小寫,可以用底線(_)作為空格 (e.g. idx, ans, res, my_ans) * 常數(不會動到它的變數)建議全部大寫 (e.g. MAX_NUM, MIN_IDX) ::: :::spoiler 宣告 ##### C++要在變數名稱前放變數型態(行末還要加分號) ```cpp= int i=1; char c='A'; string s="Hello"; //STL ``` ##### Python不用,它會自己判斷 ```python= i=1 f=10/3 c='A' s="Hello" f=int(f) #強制轉型,f現在是3(無條件捨去) print(type(f)) #輸出該變數型態 ``` ::: ## 輸入輸出 >上次是教C++的,以下是Python寫法 ```python= i=input("請輸入:") #輸入 print("你輸入了:",i) #輸出 ``` :::spoiler result ![](https://hackmd.io/_uploads/SyRYagjl6.png =300x120) ::: ## 基本運算 | 運算子 | 意義 | 舉例 | 結果 | | ------ | ---------- | ------- | ------- | | + | 加 | a=1+2 | a==3 | | - | 減 | b=1-2 | b==-1 | | * | 乘 | c=1*2 | c==2 | | / | 除 | d=1/2 | d==0.5 | | % | 取餘數 | e=1%2 | e==1 | | // | 除法取整數 | f=10/3 | f==3 | | ** | 次方 | g=2**10 | g==1024 | :::info // 是無條件捨去 ::: ## if & elif ```python= a=10 if(a==5): print("a is 5") elif(a==15): print("a is 15") else: print("a is 10") #print "a is 10" ``` --- # 二、關係判斷及布林運算 ## 關係判斷 | 符號 | 意義 | | ------ | -------- | | a == b | 等於 | | a > b | 大於 | | a >= b | 大於等於 | | a < b | 小於 | | a <= b | 小於等於 | | a != b | 不等於 | ## 位元運算 #### and : & | & | 0 | 1 | | - | - | - | | **0** | 0 | 0 | | **1** | 0 | 1 | #### or : | | \| | 0 | 1 | | - | - | - | | **0** | 0 | 1 | | **1** | 1 | 1 | #### xor : ^ | ^ | 0 | 1 | | - | - | - | | **0** | 0 | 1 | | **1** | 1 | 0 | #### not : ! | ! | | | - | - | | **0** | 1 | | **1** | 0 | ## 布林運算子 計算布林值之間的關係,回傳布林值 #### and : && | && | True | False | |----| ---- | ----- | | True | True | False | | False | False | False | #### or : || | \|\| | True | False | |----| ---- | ----- | | True | True | True | | False | True | False | #### not : ! | ! | True | False | | ---- | ----- | ----- | | ---- | False | True | # 三、迴圈 ## for-loops ```python= for i in range(10): print(i) # result:0 1 2 3 4 5 6 7 8 9 # i從0開始,跑十次(跑到9) for i in range(5,10): print(i) # result:5 6 7 8 9 # i從5開始,跑到9 ``` ## while-loops ```python= i=0 while(i<10): print(i) i=i+1 # result:0 1 2 3 4 5 6 7 8 9 # i從0開始,只要i<10成立就繼續執行 while(True): print("true") # result:輸出無限次"true" # 無窮迴圈 ``` :::warning 記得冒號之後(你要放在迴圈裡的東西)要縮排,很重要 ::: ## continue & break >如果你想要跳過某次迴圈,用continue >如果想要跳出迴圈,用break ```python= i=0 while(True): i=i+1 if(i==5): continue elif(i==10): break print(i) #1 2 3 4 6 7 8 9 ``` --- # 四、好用的資料結構 ## list >就是陣列 #### 宣告 ```python= l1=[] #創建一個空的list l2=[1, 2, 3] #創建一個裡面有1,2,3的list l3=['a', 'b', 'c'] #創建一個裡面有a,b,c的list l4=[0.5, 'A', 100] #不同型態也可以放一起 l5=[[[]],[],[]] #也可以在list裡放list(形成多維陣列) ``` #### 取值 ```python= l=[1, 2, 3] print(l[0]) #輸出1 print(l[1]) #輸出2 print(l[-1]) #輸出3 print(l) #輸出[1,2,3] print(l[0:3]) #輸出1,2,3 #輸出index=0~2的元素(不包含index=3) for i in l: print(i) # 輸出1,2,3 #以for遍歷容器 ``` #### 加值&改值 ```python= l=[1, 2, 3] l.append(4) #[1, 2, 3, 4] l.append(5) #[1, 2, 3, 4, 5] l.insert(2, 6) #[1, 2, 6, 3, 4, 5] l[1]=7 #[1, 7, 6, 3, 4, 5] l.pop() #[1, 7, 6, 3, 4] l.pop(0) #[7, 6, 3, 4] del l[0:2] #[3, 4] l.remove(4) #[3] l.clear() #[] ``` #### 尋找&其他 ```python= l=[1, 2, 3, 4, 5] print(l.index(4)) #輸出3 print(l.index(6)) #error print(l.count(2)) #輸出1 l=[2, 2, 2, 2, 2] #[2, 2, 2, 2, 2] print(l.count(2)) #輸出5 ``` ## dict(dictionary) >像是每本書的頁碼(key)和內容(value)一一對應 :::info d = {key1: value1, key2: value2} ::: #### 宣告 ```python= d=dict() #創建一個空的dict d1={} #創建一個空的dict d2={'A':10, 'B':100} #key是"A"的值為10,key是"B"的值為100 d3={10:'a' , 'apple':5, 'C':1000} #這樣也行 ``` :::danger 字典裡元素的 value 可以是任何的資料型態,如字串、整數、list。 但 key 必須是唯一且不可變的,也就是在寫程式時不可隨意更更改,如整數、字串、tuple。 ::: #### 取值 ```python= d={10:'a' , 'apple':5, 'C':1000} print(d[10]) #'a' print(d['apple']) #5 print(d['C']) #1000 print(d['hello']) #key error ``` #### 加值&改值 ```python= d={10:'a' , 'apple':5, 'C':1000} d[10]='A' #{10:'A', "apple":5, 'C':1000} d['apple']='HELLO' #{10:'A', "apple":'HELLO', 'C':1000} d['new']="value" #{10:'A', "apple":'HELLO', 'C':1000, 'new':'value'} del d['apple'] #{10:'A', 'C':1000, 'new':'value'} ``` #### 尋找&其他 ```python= d={10:'a' , 'apple':5, 'C':1000} print(len(d)) #3 print(d.keys()) #印出所有key print(d.values()) #印出所有value print(d.items()) #印出所有key+value print('apple' in d) #檢查key是否在這個dict中,是則回傳True,否則回傳False ``` ## set >很方便,可以做交集、並集、差集之類的操作 #### 宣告 ```python= s1=set() #創建一個空的set s2={1, 2, 3} #有元素1,2,3的set s3=set(["apple", 10, 'A']) #這樣也行,從一個list創建set ``` :::danger 創建空集合只能用set( )而非s={ },因為會變成創建空的dict ::: #### 加值 ```python= s={1,2,3} s.add(4) #{1, 2, 3, 4} s.add(3) #{1, 2, 3, 4} s.update(5) #{1, 2, 3, 4, 5} s.update([6, 7]) #{1, 2, 3, 4, 5, 6, 7} ``` :::info 如果你要用list或其他資料結構加值的話請用update( ) 而且set裡不會有重複元素 ::: #### 移除元素 ```python= s={1,2,3} s.remove(1) #{2, 3} s.remove(4) #error s.discard(2) #{3} s.discard(4) #{3} ``` :::info 如果該元素不在set裡的話用remove( )會報錯,但用discard( )不會 ::: #### 其他操作 ```python= s1={1, 2, 3, 4, 5} s2={3, 4, 5, 6, 7} print(len(s1)) #5 print(set.intersection(s1, s2)) #取交集,回傳{3, 4, 5} #也可以寫成print(s1 & s2) print(set.union(s1, s2)) #聯集,回傳{1, 2, 3, 4, 5, 6, 7} #print(s1 | s2) print(set.difference(s1, s2)) #差集(s1-(s1&s2)),回傳{1, 2} #print(s1 - s2) print(set.symmetric_difference(s1, s2)) #對稱差集,回傳{1, 2, 6, 7} #print(s1 ^ s2) ``` ![](https://hackmd.io/_uploads/ryvx0Toxp.png) ### 以上為粗略的容器介紹,還有很多種資料結構,以及很多我沒有介紹的method,如果有興趣的可以自行google --- # 五、宣告函式 ```python= #宣告函式 def my_func(): print("Hello!") #呼叫函式 my_func() ``` :::info 用 def 來宣告一個函式,記得要有冒號和縮排 ::: :::danger 先宣告再呼叫,不然會error ::: :::spoiler result ![](https://hackmd.io/_uploads/rJP4pAsl6.png =200x100) ::: ### 如果想要傳入參數 ```python= def sum(a, b, c): print(a+b+c) sum(1, 2, 3) #a=1, b=2, c=3 #print 6 ``` ### 如果想要回傳值 ```python= def sum(a, b, c): return a+b+c ans=sum(1, 2, 3) print(ans) #a=1, b=2, c=3 #print 6 ``` ### 試試看在函式裡放函式? ```python= def my_func(a, b, c): def func1(_a, _b, _c): #內部函式 return _a+_b+_c def func2(_a, _b, _c): #內部函式 return _a*_b*_c ans1=func1(a, b, c) ans2=func2(c, b, a) return ans1-ans2 ans=my_func(1, 3, 5) print(ans) # print -6 ``` :::danger 只有在my_func( )內才能呼叫func1( )和func2( ),因為他們是my_func( )的內部函式 如果在其他地方呼叫的話可能會出錯 ::: :::danger 同樣的,因為ans1和ans2是在函式內宣告的變數,也只能在該函式內使用 ::: ### global >猜猜會輸出什麼? ```python= a=10 def func(): a=100 print(a) func() print(a) ``` :::spoiler ans ![](https://hackmd.io/_uploads/BJe8Rl2ea.png =200x90) >欸?為什麼不是100 100? :::info 因為剛剛前面提到的,基本上在函式裡作的一切變數改值都跟外界無關 所以a=100只會在func( )裡面生效 func( )外的a依然是10 ::: ## ```python= a=10 def func(): global a #將a設為全域變數 a=100 print(a) func() print(a) ``` :::spoiler result ![](https://hackmd.io/_uploads/ByXOl-hg6.png =180x90) >成功了 ::: --- # 六、import >把別人的東西拿來用,好爽 #### 用法 ```python= import numpy import datetime import pandas ``` #### 取別名 ```python= import numpy as np import datetime as dt import pandas as pd ``` #### 有些插件包要先安裝才能import ``` pip install numpy ``` --- # 沒了 ### 大家段考加油 ### 我沒了 ![](https://hackmd.io/_uploads/BJwISb2gT.jpg =400x400) # 參考資料 https://steam.oxxostudio.tw/category/python/basic/import.html