# 第三天-運算子 > [color=#40f1ef][name=LHB阿好伯, 2020/11/20][:earth_africa:](https://www.facebook.com/LHB0222/) ###### tags: `Python_30` [TOC] # 算術運子 四則運算 跟R平時所用的加(+)、減(-)、乘(*)和除(/)一樣 ```python= x = 2 + 4 y = x - 6 z = (y + 4 ) * x z / x #計算9除以6的餘數 9 % 6 #計算12除3的商數 12 // 3 # 計算2的10次方 2 ** 10 # 計算4的平方根 4 ** 0.5 ``` ## 指派運算子 Python 具備一種很便利的指派運算子可以讓我們的程式更簡潔 在R中是無法使用的 | 運算子 | 範例 | 說明 | |:------:|:------:|:-------:| | += | a += b | a = a+b | | -= | a -= b | a = a+b | | *= | a *= b | a = a-b | | /= | a /= b | a = a*b | | %= | a %= b | a = a/b | | //= | a //= b | a = a//b | | **= | a **= b | a = a**b | |&=|a &= b|a = a & b | ![](https://i.imgur.com/VbdtGAR.png)| ![](https://i.imgur.com/vv4nmAZ.png)|![](https://i.imgur.com/VPnR2bi.png) |^=| a ^= b|a = a ^ b |>>=|a >>= b|a = a >> b |<<=|a <<= b|a = a << b ```python= a = 10 a = a + 10 a =+ 10 ``` ## 多重賦值 在R與Python中都可以進行多個變數同時賦值 例如**R** ```R= a <- b <- c <- 10 a b c ``` :::success 10 10 10 ::: **Python** ```python= a = b = c = 10 a b c ``` :::success 10 10 10 ::: 在Python中甚至可以一次給不同變數賦予不同的值 ```python= a, b, c = 10, 20, 30 a b c ``` :::success 10 20 30 ::: 也可以利用這特性來進行變數的交換 ```python= a, b, c = c, b, a a b c ``` :::success 30 20 10 ::: # 關係運算子 | Operator | Description | | :--------: | :--------: | | `>` | 檢查第一個元素是否==大於==第二元素 | | | `<` |檢查第一個元素是否==小於==第二元素 | | | `==` | 檢查第一個元素是否==等於==第二元素 | | | `>=` | 檢查第一個元素是否==大於或等於==第二元素 | | | `<=` | 檢查第一個元素是否==小於或等於==第二元素 || | `!=` | 檢查第一個元素是否==不等於==第二元素 | | is:如果兩個變量是同一個對象(x in y),則返回true is not:如果兩個變量都不是同一個對象(x is not y),則返回true in:如果查詢列表中包含某個項目(y in x),則返回True not in:如果查詢列表中沒有特定項(y not in x),則返回True # 邏輯運算子 |R Operator|Python Operator | Description | | :--------: | :--------: |:--------: | |`&`| and | AND 兩個關係必須為TRUE,則結果為 TRUE | |shift + \ | or | OR 兩個關係一方為TRUE,則結果為 TRUE| |`!`| not | NOT 得到相反邏輯值,將原本TRUE的結果改成FALSE| ```python= print('1 is 1', 1 is 1) # True - 數據值相同 print('1 is not 2', 1 is not 2) # True print('A in Asabeneh', 'A' in 'Asabeneh') # True - 在字符串中找到 print('B in Asabeneh', 'B' in 'Asabeneh') # False - 沒有大寫字母B print('coding' in 'coding for all') # True print('a in an:', 'a' in 'an') # True print('4 is 2 ** 2:', 4 is 2 ** 2) # True ``` 全文分享至 https://www.facebook.com/LHB0222/ 有疑問想討論的都歡迎於下方留言 喜歡的幫我分享給所有的朋友 \o/ 有所錯誤歡迎指教 # [:page_with_curl: 全部文章列表](https://hackmd.io/@LHB-0222/AllWritings) ![](https://i.imgur.com/47HlvGH.png)