Udemy課程:[100 Days Of Code(Dr. Angela Yu)](https://www.udemy.com/course/100-days-of-code/) # Day 10 - Beginner - Functions with Outputs ###### tags: `python` `Udemy` `100 Days Of Code` 2021.02.24(Wed.)~02.26(Fri.) ## ● 前言 / 心得 這單元主要提到print跟return的差別,然後沒太多新的內容,除了recursion之外,像是dictionary、while loop等等都是前面學過的內容,加上這單元基本上都是跟著老師的步驟,我覺得有相對簡單些。 ## ● 上課筆記 ## 0.code [day-10-start](https://repl.it/@tina0915tw/day-10-start#main.py) [day-10-end](https://repl.it/@tina0915tw/day-10-end#main.py) [day-10-1-exercise](https://repl.it/@tina0915tw/day-10-1-exercise#README.md) [calculator-start](https://repl.it/@tina0915tw/calculator-start#main.py) [calculator-debug-solution](https://repl.it/@tina0915tw/calculator-debug-solution#main.py) [calculator-final](https://repl.it/@tina0915tw/calculator-final#main.py) ## 1.[day-10-1-exercise](https://repl.it/@tina0915tw/day-10-1-exercise#README.md) * 我的作法: ```python= def is_leap(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False def days_in_month(year,month): month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if not is_leap(year): return month_days[month-1] elif is_leap(year): month_days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] return month_days[month-1] #🚨 Do NOT change any of the code below year = int(input("Enter a year: ")) month = int(input("Enter a month: ")) days = days_in_month(year, month) print(days) ``` * 老師作法: ```python= def is_leap(year): if year % 4 == 0: if year % 100 == 0: if year % 400 == 0: return True else: return False else: return True else: return False def days_in_month(year, month): month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if month > 12 or month < 1: return "Invalid month entered." if month == 2 and is_leap(year): return 29 return month_days[month - 1] #Do NOT change any of the code below 👇 year = int(input("Enter a year: ")) month = int(input("Enter a month: ")) days = days_in_month(year, month) print(days) ``` ## 2.Project部分 1. Step 1:([calculator-start](https://repl.it/@tina0915tw/calculator-start#main.py)) 先弄出一個dictionary字典,包含加減乘除。 把加減乘除的符號當作keys,然後設好的function:add、multiple......等等當作values,然後再用function去包裝。 * 作法: ```python= def add(n1,n2): return n1 + n2 def subtract(n1,n2): return n1 - n2 def mutiply(n1,n2): return n1 * n2 def devide(n1,n2): return n1 / n2 operations = { "+": add, "-": subtract, "*": mutiply, "%": devide } num1 = int(input("What's the first number?: ")) num2 = int(input("What's the second number?: ")) for symbol in operations: print(symbol) operationSymbol = input("Pick an operation from the line above: ") ans = operations[operationSymbol](num1,num2) print(f"{num1} {operationSymbol} {num2} = {ans}") ``` 2. Recursion > 一個函式當中再去呼叫它自己 * 舉例: (此例子會無限循環列印ahhhhh) ```python= def calculator(): print("ahhhhh") calculator() calculator() ```