# DAY 03 - if 陳述句 ###### tags: `python教學` `print結尾語` `if/else` `九九乘法表` ## 縮排 在python中,縮排就跟C語言的大括號一樣 ```python= age = 21 if age >= 20 : print("可以投票") else : print("不能投票") ``` ### BMI計算機 ```python= #輸入 weight = int(input("輸入體重(公斤)")) height = int(input("輸入身高(公分)")) #換公尺 sq_h = (height / 100) ** 2 BMI = weight / sq_h ``` if 數字大小判斷 ```python= if BMI < 18.5 : print("異常:過輕") elif BMI < 24: print("正常") else: print("異常",end=':') if BMI < 27: print("過重") elif BMI < 30: print("輕度肥胖") elif BMI < 35: print("中度肥胖") else: print("重度肥胖") ``` --- ### 補充 - print結尾語 print函數定義(看看就好) ```python= print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False) ``` print目前常用到的只有結尾語 通常print沒有設定結尾語時,預設是使用\n(換行符號) 所以可以將print("",end = 'XX')裡的XX換成其他東西 e.g. ```python= for i in range(1,10): print(i,end = ',') for i in range(1,10): print(i,end = ' ') ``` 輸出結果: ```python= 1,2,3,4,5,6,7,8,9, 1 2 3 4 5 6 7 8 9 ``` --- ### and & or ```python= a = 5 b = 6 c = 8 if a>c and b>a: print("兩個敘述句「都」對") if a>c or b>a: print("兩個敘述句「至少有一個」對") ``` --- ### 補充 - 數字比較 python規範比較寬鬆 所以可以使用 a < b < c 這種連續比較數值的方式 e.g. ```python= score = 87 if score == 100: print("A+") elif 90<=score<100: print("A") elif 80<=score<90: print("B") elif 70<=score<80: print("C") elif 60<=score<70: print("D") else: print("F") ``` --- ### if應用 - 偵測串列內是否有值 ```python= #空串列 students = [] if students: #偵測串列裡是否有值 print("有學生") else: print("串列是空的") ``` ### if應用 - 偵測某值是否有在串列中 ```python= students = ["jack","rose","bonny","stan"] studentA = "alan" if studentA in students: print("alan在串列中") else: print("alan不在串列中") ``` --- ### inClass practice - 九九乘法表 輸出結果: ```python= 1 * 1 = 1 1 * 2 = 2 1 * 3 = 3 1 * 4 = 4 1 * 5 = 5 1 * 6 = 6 1 * 7 = 7 1 * 8 = 8 1 * 9 = 9 2 * 1 = 2 2 * 2 = 4 2 * 3 = 6 2 * 4 = 8 2 * 5 = 10 2 * 6 = 12 2 * 7 = 14 2 * 8 = 16 2 * 9 = 18 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 3 * 6 = 18 3 * 7 = 21 3 * 8 = 24 3 * 9 = 27 4 * 1 = 4 4 * 2 = 8 4 * 3 = 12 4 * 4 = 16 4 * 5 = 20 4 * 6 = 24 4 * 7 = 28 4 * 8 = 32 4 * 9 = 36 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 6 * 1 = 6 6 * 2 = 12 6 * 3 = 18 6 * 4 = 24 6 * 5 = 30 6 * 6 = 36 6 * 7 = 42 6 * 8 = 48 6 * 9 = 54 7 * 1 = 7 7 * 2 = 14 7 * 3 = 21 7 * 4 = 28 7 * 5 = 35 7 * 6 = 42 7 * 7 = 49 7 * 8 = 56 7 * 9 = 63 8 * 1 = 8 8 * 2 = 16 8 * 3 = 24 8 * 4 = 32 8 * 5 = 40 8 * 6 = 48 8 * 7 = 56 8 * 8 = 64 8 * 9 = 72 9 * 1 = 9 9 * 2 = 18 9 * 3 = 27 9 * 4 = 36 9 * 5 = 45 9 * 6 = 54 9 * 7 = 63 9 * 8 = 72 9 * 9 = 81 ``` 小提示 ```python= i," * ",j," = ",i*j ``` :::spoiler {state="close"} 解答 ```python= for i in range(1, 10): # i從1到9 for j in range(1, 10): # j從1到9 print(i ,'*', j ,'=' ,i*j,end=" ") #印出i*j=i*j ``` ::: --- ### Homework - 印星星 每隔一行多兩個* 輸出結果: ```python= * *** ***** ******* ``` :::spoiler 解答 7/10 ::: ### Homework - 加法 https://zerojudge.tw/ShowProblem?problemid=a002