--- title: Python 基礎語法 image: https://i.imgur.com/hfBqYPs.jpg tags: cpsd --- # Python :::success 有6題(0-5)小練習題,會用綠框框包起來,做做看拜託,神奇想題目想很久 ::: ## I/O 輸入與輸出 ### print() 預設 - `sep=' '` (以空格分隔) - `end='\n'` (以換行結尾) ```python print(s) # 印出s、以換行結尾 print(s1, s2, s3) # 以空格分隔印出s1 s2 s3,同樣以換行結尾 # 改變sep print("HackMD", "Github", "Python") # output: HackMD Github Python print("HackMD", "Github", "Python", sep='~~~') # output: HackMD~~~Github~~~Python # 改變end print("sun", end='!!!') # output: sun!!! ``` ### Hello, World! ```python print("Hello, World!") # output: Hello, world! ``` $print(x)\rightarrow輸出x$ :::info print要小寫 ```python print Print p r i n t RRINT ``` 變色代表電腦認得這個字 Syntax highlighting 為了增加可讀性、減少錯誤率的功能 ::: :::info ```python print( "Hello, World!" ) # 東西之間可以空格 # output: Hello, world! print "Hello, World!" # py3括號不能少(py2就沒差) # SyntaxError: Missing parentheses in call to 'print'. print(Hello, World!) # 文字要加引號 # SyntaxError: invalid syntax ``` ::: ### 跳脫字元 嘗試輸出 `'`(單引號)、`"`(雙引號)、`\` 輸出 the "quotes" in the quotes ```python print("the "quotes" in the quotes") # SyntaxError: invalid syntax ``` 法一: 輸出單引號用雙引號包、輸出單引號用單引號包 ```python print('the "quotes" in the quotes') # output: the "quotes" in the quotes print("the 'quotes' in the quotes") # output: the 'quotes' in the quotes ``` 法二:(推薦) 加 跳脫字元`\` 讓加在後面的字元**跳脫**本身的意義而具有其他意義 `"`本身的意義是用來刮住一段文字,賦予它們字串的意義 加上跳脫字元後,`\"`則表示雙引號 ```python print("\"") # output: " ``` ``` \\ -> 反斜線 \' -> 單引號 \" -> 雙引號 \n -> 換行 \t -> tab(定位字元) \b -> backspace ``` ### input() ```python s = input() s = input("輸入前想顯示的字") # 讀取輸入直到換行(enter),並將輸入存到s name = input() print("Hello", name) # input: Sun # output: Hello Sun ``` :::info 讀進來的輸入都會是字串的形式 ::: :::success ### 小練習0 輸出下面的文章,嘗試只使用一次print()並不使用多行字串 ``` Think about the last time you felt a negative emotion like stress, anger, or frustration. What was going through your mind as you were going through that negativity? Was your mind cluttered with thoughts? Or was it paralyzed, unable to think? The next time you find yourself in the middle of a very stressful time, or you feel angry or frustrated, stop. Yes, that's right, stop. Whatever you're doing, stop and sit for one minute. While you're sitting there, completely immerse yourself in the negative emotion. Allow that emotion to consume you. Allow yourself one minute to truly feel that emotion. Don't cheat yourself here. Take the entire minute--but only one minute--to do nothing else but feel that emotion. When the minute is over, ask yourself, "Am I wiling to keep holding on to this negative emotion as I go through the rest of the day?" Once you've allowed yourself to be totally immersed in the emotion and really fell it, you will be surprised to find that the emotion clears rather quickly. If you feel you need to hold on to the emotion for a little longer, that is OK. Allow yourself another minute to feel the emotion. When you feel you've had enough of the emotion, ask yourself if you're willing to carry that negativity with you for the rest of the day. If not, take a deep breath. As you exhale, release all that negativity with your breath. This exercise seems simple--almost too simple. But, it is very effective. By allowing that negative emotion the space to be truly felt, you are dealing with the emotion rather than stuffing it down and trying not to feel it. You are actually taking away the power of the emotion by giving it the space and attention it needs. When you immerse yourself in the emotion, and realize that it is only emotion, it loses its control. You can clear your head and proceed with your task. Try it. Next time you're in the middle of a negative emotion, give yourself the space to feel the emotion and see what happens. Keep a piece of paper with you that says the following: Stop. Immerse for one minute. Do I want to keep this negativity? Breath deep, exhale, release. Move on! This will remind you of the steps to the process. Remember; take the time you need to really immerse yourself in the emotion. Then, when you feel you've felt it enough, release it--really let go of it. You will be surprised at how quickly you can move on from a negative situation and get to what you really want to do! ``` ::: :::success ### 小練習1 輸入為兩個名子,以換行分隔,一行一個 請跟他們兩個打招呼 ``` input: Sun input: Rain output: Hi, Sun and Rain. ``` 也可以看完**變數**那章再回來做這題 hits: 你可能需要改變sep ::: --- ## Data Type 資料型態 ### type() ```python print(type("Hello, World!")) # output: <class 'str'> ``` $type(x)\rightarrow x的型態$ - **str** (string 字串) ``` "Hello, World!" "This is a string" "A" 'hello~' "嗨" 'another string' ``` - **int** (integer 整數) ``` 2022 123 0 2147483647 20030122 10000000000000000000000000000000000 666 ``` - **float** (浮點數) ``` 2022.0228 2e9 (2*(10^9)) 0.0 99e-9 (99*(10^(-9))) 3.1415926 1.22 ``` - **bool** (boolean 布林值) ``` True False ``` - 其他 - list - dict - tuple - set - map - NoneType :::info 型態是電腦理解資料或處理資料間運算的依據 ```python print(1+1) # output: 2 print('1'+'1') # output: 11 print('1'+1) # TypeError ``` ::: ### 型別轉換 ```python print("2022"*2) # output: 20222022 print(int("2022")*2) # output: 4044 print(type(int("2022"))) # output: <class 'int'> ``` $A(x)\rightarrow 把x轉為A的型態$ --- ## Arithmetic Operators 算數運算子 - `+` 加 - `-` 減 - `*` 乘 - `**` 次方 - `/` 除 - `//` 求商 - `%` 求餘(模運算) ```python print(10+6) # output: 16 print(10-6) # output: 4 print(10*6) # output: 60 print(10**6) # output: 1000000 print(10/6) # output: 1.6666666666666667 print(10//6) # output: 1 print(10%6) # output: 4 print('10'+'6') # output: 106 print('10'*6) # output: 101010101010 ``` :::info 求商、求餘遵守 $被除數=除數\times商數+餘數$ 求商運算在 Python 中是除的向下取整 ps. 在 C++ 是向零取整 ```python # -5 = 2*(-3)+1 print((-5)/2) # output: -2.5 print((-5)//2) # output: -3 (-2.5向下取整) print((-5)%2) # output: 1 ``` ::: :::warning 不像 C++,Python3 的整數基本上不存在大小限制 他可以很輕鬆地計算googol ($10^{10^2}$) ```python print(10**(10**2)) # output: 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000 print(2**1000) # output: 10715086071862673209484250490600018105614048117055336074437503883703510511249361224931983788156958581275946729175531468251871452856923140435984577574698574803934567774824230985421074605062371141877954182153046474983581941267398767559165543946077062914571196477686542167660429831652624386837205668069376 ``` ::: :::success ### 小練習2 半路殺出兩個向量$A(A_1, A_2, A_3), B(B_1, B_2, B_3)$ 請你算出它們的內積值$(A_1*B_1+A_2*B_2+A_3*B_3)$ 輸入為兩行,分別代表兩個向量 但大家可能對輸入輸出還不熟,軟研是個開心學習又溫暖的地方 所以我先幫大家打好一些了,但要注意型態喔 ```python A1, A2, A3 = input().split(' ') B1, B2, B3 = input().split(' ') ans = ??? print(ans) ``` ``` input: 1 2 3 input: 2 3 4 output: 20 ``` ::: :::success ### 小練習3 長江後浪推前浪 ~~前浪死在沙灘上~~,學測考完不久,又是新的倒數開始的時候 老薛也想參加下次學測,他想知道自己還剩多少時間準備 但是他不喜歡只用日數來倒數,請幫他把日數換成月數+日數使日數最小 輸入為一行,包含一個數字表示剩餘日數 請輸出剩餘幾個月又幾天,中間空一格,假設一個月都是30天 ``` input: 323 output: 10 23 ``` ::: --- ## Variables 變數 ### 命名規則 - 只能用 A-Z, a-z, 0-9, _ - 不能以數字開頭 - 不能與關鍵字相同 - False, None, True - and, del, in, is, lambda, not, or - as, assert, break, continue, from, global, import, nonlocal, pass, raise, return, yield - else, elif, except, finally, for, if, try, while, with - class, def - 命名有意義會更好 ### Assignment Operator 指派運算子 `=`是 Python 最基本的指派運算子 將等號右邊的值拷貝給左邊的變數 ```python a = 1 b = 'abc' c = True d = None e = 1+2/3*4-6**8 pi = 3.14 abc = b ``` 等號可以與其他運算子合用,將結果直接存回原變數中 ```python a += 1 # a = a+1 a -= 2 # a = a-2 a *= 4 # a = a*4 a /= pi # a = a/pi ``` :::success ### 小練習4 神奇上學期的成績全距是60到100,但他特別喜歡偶數的成績 他會給你一個範圍,請你找出這個範圍有幾個偶數 輸入有兩行,各包含一個正整數,請輸出這個範圍(包含頭尾)有幾個偶數 試著不用`if`完成這個程式 ``` input: 2 input: 50 output: 25 ``` hits: 藉由1-x%2可以判斷正整數x是不是偶數 ::: ## Comments 註解 ### 單行註解 ```python # 那一行井字之後的都是註解 print(pi) # 不管打什麼都不會被執行 a = int(input()) # 通常寫一些有用的東西 a **= 2 # 註解是給未來的自己或跟你一起寫code的人看的 # 很重要 ``` ### 多行註解 ```python inp = input() """這裡是多行註解的第一行 print(i) e == 3 == pi 在這裡的都不會被直譯器執行 """ ''' 單引號的也可以 多行註解也是多行字串 換行會被轉成\n''' print(''' 像是這樣 這裡就會被輸出''') # output: # 像是這樣 # 這裡就會被輸出 ``` ## 補充 ### 其他運算子 - Comparison Operator 關係運算子 - `<` 小於 - `>` 大於 - `<=` 小於等於 - `>=` 大於等於 - `==` 相等 - `!=` 不相等 - Logical Operators 邏輯運算子 - `and` 且 - `or` 或 - `not` 非 - Bitwise Operator 位元運算子 - `&` 位元且 - `|` 位元或 - `^` 位元異或 - `~` 位元反 - Shifting Operator 位移運算子 - `>>` 向右位移 - `<<` 向左位移 ```python print(1 < 3) # output: True print(4 != 0) # output: True print(True and False) # output: False print(not(True and True)) # output: False print(200 | 99) # output: 258 ''' 200的二進位表示為11001000 99的二進位表示為01100011 對每個位元分別做OR運算得11101011 其十進位表示為235 ''' print(256 << 2) # output: 1024 print(10 >> 1) # output: 5 ''' 位元向左位移n位相當於乘n次2 位元向右位移n位相當於除n次2 256乘2的2次方等於1024 10除2的1次方等於5 ''' ``` :::success ### 小練習5 神奇的女朋友很喜歡按開關~~醒醒吧我沒有女朋友~~ 如果用1代表開、0代表關,寫個程式幫她切換開關吧 輸入為一行,包含一個0或一個1,若是0則輸出1、1則輸出0 試著不用`if`完成這個程式 ``` input: 0 output: 1 input: 1 output: 0 ``` :::