--- title: 2020 KGHS i2trc2 Python --- # Python Basic Syntax - Control Flow ###### tags:`2020KGHS` `i2trc2` [Toc] # Condition ## If else ```python= if x < 0: x = 0 print('Negative changed to zero') elif x == 0: print('Zero') elif x == 1: print('Single') else: print('More') ``` ## For Loop ### Iterating over a object Iterating over a list object ```python= words = ['cat', 'window', 'defenestrate'] for w in words: print(w, len(w)) ``` Iterating over a dict object ```python= people = {1: {'Name': 'John', 'Age': '27', 'Sex': 'Male'}, 2: {'Name': 'Marie', 'Age': '22', 'Sex': 'Female'}} for p_id, p_info in people.items(): print("\nPerson ID:", p_id, end=" ") print(", Info:", p_info) ``` :::warning 若在 iteration 過程中新增或刪除元素,會造成執行時期錯誤,因此若要刪除元素通常會對 list 或 dict 做 copy ```python= # Strategy: Iterate over a copy for user, status in users.copy().items(): if status == 'inactive': del users[user] # Strategy: Create a new collection active_users = {} for user, status in users.items(): if status == 'active': active_users[user] = status ``` ::: ### Iterating over a range of number ```python= for i in range(5): print(i) for i in range(0, 10, 3): print(i) 0, 3, 6, 9 a = ['Mary', 'had', 'a', 'little', 'lamb'] for i in range(len(a)): print(i, a[i]) ``` ### enumerate 當你同時需要 index 跟 value 的時候特別好用 ```python= for i,a in enumerate(a): print(i,a) ``` ### zip 當你有兩個以上的 list 或 dict 需要同時取元素時 ```python= A = [0, 1, 2, 3, 4] B = [4, 3, 2, 1, 0] for a, b in zip(A, B): print(a, b) ``` ### break / continue 中斷迴圈 or 略過這次(跳到下一次),基本上和 C 的用法是一樣的 ```python= for num in range(2, 10): if num % 2 == 0: print("Found an even number", num) continue print("Found an odd number", num) ``` ## While Loop 用法跟 C 幾乎都是一樣的 ```python= while True: pass ``` :::info 注意在 python 中,關係運算要用 `and` `or` `not` ```python= while x <= 0 and y >= 1: x += 1 y -= 1 ``` ::: ## Defining functions 和 C 的 function 最大的不同是 除了可以好幾個輸入,也可以好幾個輸出喔!! ```python= def calculator(a, b): return a+b, a-b, a*b, a/b x, y, z, w = calculator(1, 2) ``` ### Default argument value ```python= def calculator(a=1, b=2): return a+b, a-b, a*b, a/b x, y, z, w = calculator() ``` 當 L 不存在時,自動建立 ```python= def f(a, L=None): if L is None: L = [] L.append(a) return L ``` # Reference 1. [Python document](https://docs.python.org/3/tutorial/controlflow.html) 2. Secret in Python 1. [Pointers in Python: What's the Point?](https://realpython.com/pointers-in-python/) 2. [Primer on Python Decorators](https://realpython.com/primer-on-python-decorators) 3. [Extending Python With C Libraries and the “ctypes” Module](https://dbader.org/blog/python-ctypes-tutorial)