Udemy課程:[100 Days Of Code(Dr. Angela Yu)](https://www.udemy.com/course/100-days-of-code/) # Day 3 - Beginner - Control Flow and Logical Operators ###### tags: `python` `Udemy` `100 Days Of Code` 2021.01.20(Wed.) ## ● 前言 / 心得 一開始從if / else開始上,跟JavaScript很不一樣,打個冒號就可以了,也不用括號或是中括號,相對簡單很多。 不過有個比較不習慣的是"elif",因為在JavaScript裡是利用"else if"代表。 另外還有 and 跟 or也很不一樣,在python中,是沒有"&&"跟"||"的,取而代之的是"and"跟"or","&"跟"|"也可以,只是比較的變數是數值變量的話,"and"跟"or"是依據是否非0來決定輸出,而"&"跟"|"表示位運算。 ## ● 上課筆記 ## 0.code [day-3-start](https://repl.it/@tina0915tw/day-3-start#main.py) [day-3-1-exercise](https://repl.it/@tina0915tw/day-3-1-exercise#main.py) [day-3-end](https://repl.it/@tina0915tw/day-3-end#main.py) [day-3-2-exercise](https://repl.it/@tina0915tw/day-3-2-exercise#main.py) [day-3-3-exercise](https://repl.it/@tina0915tw/day-3-3-exercise#main.py) [day-3-multiple-if](https://repl.it/@tina0915tw/day-3-multiple-if#main.py) [day-3-4-exercise](https://repl.it/@tina0915tw/day-3-4-exercise#main.py) [day-3-5-exercise](https://repl.it/@tina0915tw/day-3-5-exercise#main.py) [treasure-island-end](https://repl.it/@tina0915tw/treasure-island-end#main.py) ## 1.if / elif / else / multiple if * #### if / else ```python= water_level = 50 if water_level > 80: print("Drain water") else: print("Continue") ``` 上面的程式碼意思,想像有一個浴缸,當你開始放水後,如果水高度超過排水口,水就會"Drain water",反之則繼續放水。 * #### if / elif / else ```python= age = int(input("What is your age? ")) if age < 12: bill = 5 print("Child tickets are $5.") elif age <= 18: bill = 7 print("Youth tickets are $7.") elif age >= 45 and age <= 55: print("Everything is going to be ok. Have a free ride on us!") else: bill = 12 print("Adult tickets are $12.") ``` 多了elif就類似選擇題有多個選項,然後從最上面一個一個看下來,看哪個選項是符合的。 * #### mutiple if ```python= if condition 1: do A if condition 2: do B if condition 3: do C ``` multiple if 就是有多個if,他每個都會去檢查是否符合。舉例來說,此處符合condition 1,2則程式會執行do A,B。 ## 2.Comparison Operator | Operator | Meaning | | -------- | ----------------------- | | > | Greater then | | < | Less than | | >= | Greater then or equl to | | <= | Less than or equal to | | == | Equal to | | != | Not equal to | 補充:一個等號(=)代表你要assign一個值進去某個變數,而兩個等號(==)則是去check左邊的值是否等於右邊的值。 ## 3.解釋[day-3-3-exercise](https://repl.it/@tina0915tw/day-3-3-exercise#main.py) 1. 先知道閏年定義: On every year that is evenly divisible by 4 **except** every year that is evenly divisible by 100 **unless** the year is also evenly divisible by 400 ``` 用中文來解釋就是: 任何能以 4 整除的年份都是閏年(不過,仍必須將一個小錯誤列入考量) 所以規定能以 100 整除的年份, 同時也要能以 400 整除,才算是閏年。 ``` 把它圖像化: ![](https://i.imgur.com/Mk8pbKJ.png) 2. 解法: 利用nested if / else,加上flowchart,就很容易解開了。