Python by sicc === :::danger 請愛惜共筆,勿進行惡意刪減 ::: :::info 課程講義:https://slides.com/sicc/python ::: ## 環境建構 - [python](https://www.python.org/downloads/) - 記得勾選 `Add python.exe to PATH` - 執行:`python 你的檔案.py` - 也可以直接 `你的檔案.py` - [colab](https://colab.research.google.com/?hl=zh-tw) ## Data Type ```python= # 註解 a = 1 # int b = 1.23 # float c = "String" # String d = 'String' # String f = True # bool ''' 多行註解 ''' ``` - ascii code [維基百科](https://zh.wikipedia.org/zh-tw/ASCII) - '1' != 1 `ord('1') = 49` ![](https://upload.wikimedia.org/wikipedia/commons/thumb/1/1b/ASCII-Table-wide.svg/2560px-ASCII-Table-wide.svg.png) - 強制轉型 ```python= a = 1 # int b = float(a) # change int to float print(type(b)) # get the type of b ``` - list ```python= x = [1, 3.14, "NISRA"] x.append("Hello") print(x[0]) # 1 print(x[-1]) # Hello print(x[0:2]) # [1,3.14] print(x[1:]) # [3.14, 'NISRA', 'Hello'] print(x[:]) # [1, 3.14, 'NISRA', 'Hello'] ``` - dict ```python= x = { "name" : "John", "StudentID" : 1, "PI" : 3.14, }#dict print(x["name"]) # John print(x["StudentID"]) # 1 print(x["PI"]) #3.14 ``` ## 輸入輸出 - input ```python= str_in = input("Input what you want:") # 預設 Data Type 為 String print(str_in) int_in = int(input("Input a number:")) # int type print(int_in) a,b = input ("Enter 'A B'").split() # 以空白鍵分開輸入 print(a,b) ``` - print ```python= a = "string" b = 1234 print(a , b) print("{0:5} {1:4}".format(a,b)) print("{} {}".format(a,b)) print(f'{a} {b}') #string 1234 ``` ## Operator ### Arithmetic Operators - +, -, *, /, - % - \*\* 次方 - // 整數除法 ### Assignment Operators - = - +=, -=, *=, /= - %= - **=, //= - ... ### Compare Operator - == - \>=, <= - \>, < - != ### Logic Operators - and - or - not [Python Operators](https://www.w3schools.com/python/python_operators.asp) ## Condition ### if ```python= x = 10 if(x >= 10): # in if # in if #out if ``` ```python= x = 10 if(x >= 10){ # in if # in if # in if } #out if ``` ### if ... else, if ... elif ... else if ... else ```python= x = 10 if(x >= 10): # in if # in if else: # in else # in else ``` if ... elif ... else ```python= if(x >= 10): # in if elif(x == 9): # in elif else: # in else # out if ``` ## Loop ### for ```python= for i in range(10): print(i, end=' ') # 0 1 2 3 4 5 6 7 8 9 print() for i in range(1, 10): print(i, end=' ') # 0 1 2 3 4 5 6 7 8 9 print() for i in range(2, 10, 2): print(i, end=' ') # 2 4 6 8 print() ``` ```python= number = ["one", "two", "three"] for i in number: print(i, end=' ') # one two three ``` ```python= number = ["one","two","three"] for i in "number": print(i,end=' ') # n u m b e r ```