[4] 運算子 + 條件判斷


Posted by bessyhuang on 2023-05-10

運算子

算術運算子

名稱 算術運算子 備註
+
-
*
除 (浮點數除法) / 4/2 輸出結果為 2.0
除 (整數除法) // 9//5 輸出結果為 1
次方 ** 2**3 輸出結果為 8
取餘數 % 7%5 輸出結果為 2

賦值運算子 =

名稱 賦值運算子 備註
加法指定 += i+=8 相當於 i=i+8

比較運算子

名稱 比較運算子
等於 ==
不等於 !=
大於 >
小於 <
大於或等於 >=
小於或等於 <=
  • 寫法一 (Python)

      a = 5
      if 3 < a < 10:
          print('3 < {} < 10'.format(a))
    
      💡 只有 Python 可以這樣寫條件判斷 (3 < a < 10)!
    
  • 寫法二 (Python)
      a = 5
      if 3 < a and a < 10:
          print('3 < {} < 10'.format(a))
    
  • 寫法三 (C/C++)

      #include <stdio.h>
    
      int main()
      {
          int a = 5;
          if (3 < a && a < 10) {
              printf("3 < %d < 10", a);
          }
          return 0;
      }
    
      💡 其他程式語言必須分開寫條件判斷 (3 < a && a < 10)!
    

邏輯/布林運算子

名稱 邏輯運算子
and
or
not
💡 Python 的布林運算子,不同於其他程式語言的寫法!!!

+----------------------+
|  C / C++  |  Python  |
+----------------------+
|     &&    |   and    |
+----------------------+
|     ||    |   or     |
+----------------------+
x = 5
print(x > 3 and x < 10)
print((x > 10) or (x % 2 == 0))
print(not(x > 3 and x < 10))

成員運算子: innot in

  • in:是否包含
  • not in:是否不包含
print("or" in "forever")
# True
print("over" not in "forever")
# True

💡 與 for loop 一同搭配使用,好用!
for i in range(1, 5):
    print(i)
# 1
# 2
# 3
# 4

Conditions 條件判斷

💡 Python 沒有 switch... case...
  但 Python 有 match... case...       請參考 References [2]

command = 'Hello, World!'
match command:
    case 'Hello, World!':
        print('Hello to you too!')
    case 'Goodbye, World!':
        print('See you later')
    case other:
        print('No match found')
# Hello to you too!
  • 常見的判斷式寫法: if... else...

if else

if [condition1]:
    [statement 1]
elif [condition2]:
    [statement 2]
else:
    [statement 3]

語法

  • condition 的部份,可以選擇用 括號 () 括起來,或者 不括起來

程式碼解釋

  • 第一個判斷如果為 True 則執行 statement1 的程式碼;
  • 如果為 False 的話就跳到下面繼續判斷,直到最後的 else 才結束。

範例

  • if
      a = 33
      b = 200
      if b > a:
          print("b is greater than a")
    
  • if..elif
      a = 33
      b = 33
      if b > a:
          print("b is greater than a")
      elif a == b:
          print("a and b are equal")
    
  • if..elif..else
      a = 200
      b = 33
      if b > a:
          print("b is greater than a")
      elif a == b:
          print("a and b are equal")
      else:
          print("a is greater than b")
    
  • if..else
      a = 200
      b = 33
      if b > a:
          print("b is greater than a")
      else:
          print("b is not greater than a")
    
  • and / or / not
      a = 200
      b = 33
      c = 500
      if ((a > b) and (c > a)):
          print("Both conditions are True")
    
      a = 200
      b = 33
      c = 500
      if ((a > b) or (a > c)):
          print("At least one of the conditions is True")
    
      a = 33
      b = 200
      if not a > b:
          print("a is NOT greater than b")
    
  • Nested if
      x = 41
      if x > 10:
          print("Above ten,")
          if x > 20:
              print("and also above 20!")
          else:
              print("but not above 20.")
    
  • pass Statement

    • if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.

        a = 33
        b = 200
      
        if b > a:
            pass
      

Ternary Operators (aka. Conditional Expressions)

  • Short Hand If
      if [condition1]: [statement 1]
    
  • Short Hand If..Else
      [statement 1] if [condition1] else [statement 2]
    

範例

  • Short Hand If
      if a > b: print("a is greater than b")
    
  • Short Hand If..Else
      a = 2
      b = 330
      print("A") if a > b else print("B")
    

練習題

Lab01:最常見的閏年判斷程式

  • 閏年判斷的條件:
    • 逢四閏年
    • 逢百不閏
    • 逢四百閏

Lab02:三角形邊長判斷

  • 輸入三個整數判斷是否能組成一個三角形
  • 條件:
    • 任兩邊長和必然大於第三邊
    • 所有邊長都要大於 0
  • Input
      請輸入任意三個數值:1,1,3
      請輸入任意三個數值:2,3,0
      請輸入任意三個數值:6,6,6
    
  • Output
      1, 1, 3 can't make a triangle.
      Wrong Input
      6, 6, 6 can make a triangle.
    

Lab03:GPA 成績計算

  • 成績等級
    • S:100
    • A:90 ~ 99
    • B:80 ~ 89
    • C:70 ~ 79
    • D:60 ~ 69
    • F:59 以下
  • Input
      請輸入成績:100
      請輸入成績:87
      請輸入成績:20
    
  • Output
      S
      B
      F
    

Lab04:處理隨機生成的字串

  • 輸入欲取代的數值 replace_num (1 個字元),並隨機生成 15 位的數值 (開頭可以為 0) random_num
    • Hint: 不足的位數,需要在前面補 0。
  • 接著,根據以下條件分別處理。
    • 條件:
      • replace_num 存在於亂數中,則將之取代為 -,並輸出結果。
      • replace_num 不存在於亂數中,則 每隔 3 字元反向輸出 結果。
  • Tips: 使用 Python 內建函式
    • 字串取代: replace()
    • 字串分割: split()
    • 字串串接: join()
    • 找字串: find()
  • Input
      Please enter the number to be replaced:2
      Please enter the number to be replaced:5
      Please enter the number to be replaced:0
    
  • Output

      15 位的亂數: 628283575214762
      =>  6-8-83575-1476-
    
      15 位的亂數: 219069649267369
      =>  97999
    
      15 位的亂數: 002901995550060
      =>  --29-199555--6-
    

References

  1. Conditional Statements in Python
  2. How to Use a match case Statement in Python 3.10

#Python #operator #if..else..







Related Posts

npm套件教學

npm套件教學

XAMPP 重新安裝遇到的問題 MAC

XAMPP 重新安裝遇到的問題 MAC

從前端傳資料給後端(GET, POST)、從 PHP 連線到 MySQL 資料庫

從前端傳資料給後端(GET, POST)、從 PHP 連線到 MySQL 資料庫


Comments