# 複習一下吧 ---- ## 同向追趕問題 ---- ### 試著用你所學實現以下內容 ```python #時速單位:Km/hr,距離單位:m 輸入甲車時速=80 輸入乙車時速=20 輸入甲乙距離=100 甲追到乙所需時間:6.0s ``` ---- ```python Acar = float(input("輸入甲車時速")) Bcar = float(input("輸入乙車時速")) x = float(input("輸入甲乙距離")) delta = (Acar-Bcar)/60/60*1000 time = float(x/delta) print("甲追到乙所需時間:"+str(time)+"s") ``` ---- 但如果甲車比乙車慢怎麼辦.. --- # 條件式敘述 新的工具~ ---- ## if-流程圖(如果...就...) ![](https://hackmd.io/_uploads/HybmZEp-T.png) ###### 流程圖的形狀符號都是有意義的,所以不能隨便更改歐~ ---- #### 流程圖的[詳細資訊](https://asana.com/zh-tw/resources/what-is-a-flowchart) ---- # 舉個例子 ```python if 身高<=180: 多喝牛奶 ``` ---- ### 條件 ```python a <= b #a小於等於b a >= b #a大於等於b a == b #a等於b,不要和a = b搞混 a != b #a不等於b a == b and b == c #a等於b而且b等於c a == b or b == c #a等於b或b等於c ``` ---- ## if/else-流程圖(如果...否則...) ![](https://hackmd.io/_uploads/ryuyKEa-a.png) ---- 同樣的 ![](https://hackmd.io/_uploads/B1v8NrTZ6.png) ---- ```python! if 分數<60分: 不及格 else: 及格 ``` ---- ![](https://hackmd.io/_uploads/BkmLw86ba.png) ---- ```python if 超市有雞蛋: 買六顆蘋果 else: 買一顆蘋果 ``` ---- #### 除了使用**else**來做二分法外 #### 還可以用**elif**來做多種判別 ---- #### if/else/elif-流程圖(如果...否則如果...) ---- ![](https://hackmd.io/_uploads/HyY3i4T-a.png) ---- ## 假設福利社販賣的食品分成三類 ### 熱量>600大卡為禁止販賣食品 ### 600大卡>=熱量>240大卡為高中部食品 ### 240大卡>=熱量為國中部食品 ---- ```python if cal>600: 所有學生禁止購買! elif cal>240: 國中生禁止購買! elif cal>=0: 皆可購買! else: 這...吃的飽嗎? ``` ---- ##### 眼尖的各位肯定都有發現在if中程式的前方都有四個空格 --- ### 縮排(indentation) 在 Python 中要去判斷「哪些程式碼屬於某層級之下」不是使用大括號 {} ,而是使用縮排判斷。 ---- java ```java if(a>0){ print("a是正數"); } ``` C++ ```cpp if(a>0){ cout<<"a是正數"; } ``` Python ```python if a>0: print("a是正數") ``` ---- 因此縮排在 Python 中是十分重要的,而根據 Python的[協定PEP8](https://peps.python.org/pep-0008/) 的規定,在Python中我們會使用「四個空格」來縮排。 ###### ps 也可以直接按一下tab --- # 小練習 ---- ### 判斷成績 output ```python 輸入成績:95 你好棒! 輸入成績:60 至少及格 輸入成績:52 記得補考 輸入成績:39 直接死當 ``` ---- ```python grade = float(input("輸入成績")) if grade>=80 : print("你好棒!") elif grade>=60 : print("至少及格") elif grade>=40 : print("記得補考") else: print("直接死當") ``` --- ## 修復問題 #### 甲車比乙車慢怎麼辦 ---- #### 思路1:直接結束 ```python Acar = float(input("輸入甲車時速")) Bcar = float(input("輸入乙車時速")) if Acar <= Bcar : print("甲車追不上乙車") else: x = float(input("輸入甲乙距離")) delta = (Acar-Bcar)/60/60*1000 time = float(x/delta) print("甲追到乙所需時間:"+str(time)+"s") ``` ---- #### 思路2:讓乙追甲 ```python Acar = float(input("輸入甲車時速")) Bcar = float(input("輸入乙車時速")) x = float(input("輸入甲乙距離")) if Acar == Bcar : print("甲車追不上乙車") elif Acar < Bcar: delta = (Bcar-Acar)/60/60*1000 time = float(x/delta) print("乙追到甲所需時間:"+str(time)+"s") else: delta = (Acar-Bcar)/60/60*1000 time = float(x/delta) print("甲追到乙所需時間:"+str(time)+"s") ``` ---- #### 還有其他的嗎?
{"contributors":"[{\"id\":\"3963913a-1955-4863-b231-e15edfb3078e\",\"add\":3553,\"del\":736},{\"id\":\"35a0644c-29d6-4dd3-98eb-9df68421a475\",\"add\":1075,\"del\":1075}]","description":"條件式","title":"條件式&迴圈"}
Expand menu